# Author: Theodore Zacharia
# V0.1: 27/10/2022 - Initial Release
#
# This script provides a template to start all other scripts with
# supports arguments being passed AND takes a bunch of ids OR a file of ids as input
# Uses shell builtin function getopts
#

# *** Globals
TRACE=0
MYARG=""
INFILE=$$.tmp


# *** Functions
_usage()
{
	echo "usage: $0 [-h] [-t] [-a arg] <filesofids...|id1 id2 ... idn>"
	echo "where"
	cat <<- _EOF_
	  -h        Displays this help message
	  -t        Set trace on
_EOF_
}


# *** Mainline

# process input parameters
while getopts tha: AOPT
do
case $AOPT in
	t) TRACE=1 ;; # set TRACE mode
	a) MYARG=$OPTARG ;;
	h) _usage
	   exit 1 ;;
	*) echo "$AOPT is an invalid option" >&2
	   exit 2 ;;
esac
done

shift $((OPTIND-1))

if [ $TRACE -gt 0 ]
then
	echo "TRACE=$TRACE" >&2
	echo "MYARG=$MYARG" >&2
	echo "positional_args=$@" >&2
fi

if [ $# -lt 1 ]
then
	_usage
	exit 1
fi

if [ -f $1 ]
then
	# if the user has passed one or more files, copy these to our tmp file and use
	cat $@ > $INFILE
else
	# otherwise expect a bunch of ids, put these into our tmp file, either space or comma separated
	for AID in $@
	do
		echo $AID >> $INFILE
	done
fi

# Do main processing from here

while read AID
do
	echo "$AID"
done<$INFILE

# clean up
rm -f $INFILE