#!/bin/bash -e
#  an options / config loader for programs in any language, based on net2sh_init

# TODO put list of options in on var so programs can check no typos?
# TODO or programs could somehow list those options they can accept?  :/
# TODO **** maybe it could be based on the defaults config file!  every option must be listed there with its default vaule
#   could also check other conf files do not introduce new vars
#   Trouble with this, it's getting a bit complex to implement.
#   Might work nice if the shell had a "no new vars" option i.e. "set new var -> fail"

set -a
dir=$PWD
work_dir=$dir/.net.$$     # but don't create or remove $work_dir, might not be needed.  or we could?
prog_path=$(which "$1")   # TODO skip which if unneeded, e.g. absolute path?
prog_dir=`dirname "$(readlink -f "$(which "$1")")"`
shift
prog=${prog_path##*/}
prog_stem=${prog%%.*}
conf=$prog_stem.conf
conf_file_var=${prog_stem}_conf
PATH="$prog_dir:$prog_dir/sub:$prog_dir/use:$PATH"
PERL5LIB="$prog_dir:$prog_dir/perl:$PERL5LIB"
for C in "$prog_dir/$conf" "/etc/default/$prog" "/etc/$conf" "$HOME/.config/$conf" "./$conf" "${!conf_file_var}"; do
	if [ -e "$C" ]; then . "$C"; fi
done
. opts
opts_got=1

exec "$prog_path" "$@"

# trap '
# 	kill -TERM $_subs 2>/dev/null
# 	wait
# 	trap - EXIT
# 	find "$work_dir" \( -type p -o -type l \) -print0 |
# 	  xargs --no-run-if-empty -0 rm -f
# 	rmdir "$work_dir"
# 	exit
# ' HUP INT QUIT TERM PIPE EXIT
# mkdir "$work_dir"
# set +e
