#!/bin/sh
# Copyright (C) 2012 - 2018 FARGOS Development, LLC
# Get sandbox attributes
# $Id$
# getsbattr [-v] --sb sandboxName [--rc rcFile] attr

rcFile="${HOME}/.sandboxrc" # default
sbName="${SB_NAME}"	# default is current sandbox
attrList=""
verbose=0
nullResponse="[undefined]"

while test $# -gt 0
do
	case "${1}" in
	-h | -help | --help)
		printf "usage: %s [-v] [--null] [--sb sandboxName] [--rc rcFile] attrName ...\n" "${0}" >&2
		printf "  -v = prefix results with attribute name\n" >&2
		printf "  --null = report null string rather than [undefined]\n" >&2
		printf " NOTE: exit status will be 1 if any attribute is null\n" >&2
		exit 1
		;;
	-sb | --sb)
		sbName="${2}"
		shift
		;;
	-rc | --rc)
		rcFile="${2}"
		shift
		;;
	-v)
		verbose=`expr ${verbose} + 1`
		;;
	-null | --null)
		nullResponse=""
		;;
	-*)
		printf "%s: unrecognized option \"%s\"\n" "${0}" "${1}" >&2
		exit 1
		;;
	*)
		attrList="${attrList}${attrList:+ }${1}"
		;;
	esac
	shift
done

if test -z "${sbName}"
then
	printf "%s: sandbox name was not specified.\n" "${0}" >&2
	exit 1
fi

if test ! -e "${rcFile}"
then
	printf "%s: rc file \"%s\" does not exist.\n" "${0}" "${rcFile}" >&2
	rcFile="/dev/null"
fi

exitStatus=0
for attr in ${attrList}
do
	result=`awk "/SB_${sbName}_${attr}_/ { for(i=2;i<NF;i+=1) { printf(\"%s \", \\$i); } print \\$NF; } { next; }" "${rcFile}"`
	if test -z "${result}"
	then
		result="${nullResponse}"
		exitStatus=1
	fi
	if test ${verbose} -ge 1
	then	# display attribute name in front of result
		printf "%s = %s\n" "${attr}" "${result}"
	else	# just display attribute name
		printf "%s\n" "${result}"
	fi
done
exit ${exitStatus}
