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

rcFile="${HOME}/.sandboxrc"
sbName="${SB_NAME}"	# default is current sandbox
attrList=""

while test $# -gt 0
do
	case "${1}" in
	-h | -help | --help)
		printf "usage: %s [--sb sandboxName] [--rc rcFile] attrName=value ...\n" "${0}" >&2
		exit 1
		;;
	-sb | --sb)
		sbName="${2}"
		shift
		;;
	-rc | --rc)
		rcFile="${2}"
		shift
		;;
	-*)
		printf "%s: unrecognized option \"%s\"\n" "${0}" "${1}" >&2
		exit 1
		;;
	*)
		# name=val gets converted to name <space> val
		pairs=`echo $1 | awk -F = '{ print $1 " " $2; }'`
		attrList="${attrList}${attrList:+ }${pairs}"
		;;
	esac
	shift
done

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

setMode=0
keysToDelete=""
for attr in ${attrList}
do
	if test ${setMode} -eq 0
	then
		keysToDelete="${keysToDelete} -e /SB_${sbName}_${attr}_/d"
		setMode=1
	else # reset to 0
		setMode=0
	fi
done

if test -z "${keysToDelete}"
then
	printf "%s: No attributes specified, nothing to do.\n" "${0}" >&2
	exit 1
fi
if test ${setMode} -ne 0
then
	printf "%s: Missing value for attribute.\n" "${0}" >&2
	exit 1
fi

tmpFile="`dirname ${rcFile}`/newsbrcfile.txt"
trap "rm -f ${tmpFile}" EXIT

sed ${keysToDelete} "${rcFile}" > "${tmpFile}"

for attr in $attrList
do
	if test ${setMode} -eq 0
	then
		lastAttr="${attr}"
		setMode=1
	else
		printf "SB_${sbName}_${lastAttr}_\t${attr}\n" >> "${tmpFile}"
		setMode=0
	fi
done
sort "${tmpFile}" > "${rcFile}"
exit 0
