export LC_ALL=C LANG=C LANGUAGE=C

# Global fallback variables: very crude defaults. These ones can be
# overriden in multiple places.
hasher_dir=/usr/share/hasher
quiet=
verbose=
PROG="${0##*/}"

# Load user-wide config with some default variables
[ -r $HOME/.sptrc ] && . $HOME/.sptrc

. $spt_dir/functions

# Store parameters for later reuse
COMMAND_LINE_PARAMS="$@"

# Parse parameters for the first time. Determine work directory.
TEMP=`getopt -n $PROG -o w:,o:,v,q,V,h -l work:,options:,verbose,help,quiet,version -- $COMMAND_LINE_PARAMS` || show_usage
eval set -- "$TEMP"

while :; do
	case "$1" in
	-w|--work) shift; work_dir="$1"
		;;
	-o|--options) shift
		;;
	-h|--help) show_help
		;;
	-V|--version) show_version
		;;
	--) shift; break
		;;
	esac
	shift
done

#[ "$#" -eq 0 ] || show_usage "Too many arguments: $#"
[ -z "$work_dir" -a -d profile ] && work_dir=$PWD
[ -z "$work_dir" -a -d ../profile ] && work_dir=$PWD/..
[ -n "$work_dir" ] || Fatal 'Work directory not defined'

# Set up variables calculated from work directory, if they were not
# overridden before (in user config).
[ -z "$profile_dir" ] && profile_dir=$work_dir/profile
[ -z "$out_dir" ] && out_dir=$work_dir/out
[ -z "$tmp_dir" ] && tmp_dir=$work_dir/tmp
[ -z "$chroot" ] && chroot=$work_dir/chroot

# load global config variables from profile
. $profile_dir/config || Fatal "File \`$profile_dir/config' not found"

# Parse parameters for the second time. Determine widely used options
# and apply command line overrides.
TEMP=`getopt -n $PROG -o w:,o:,v,q,V,h -l work:,options:,verbose,help,quiet,version -- $COMMAND_LINE_PARAMS` || show_usage
eval set -- "$TEMP"

while :; do
	case "$1" in
	-w|--work) shift
		;;
	-v|--verbose) verbose=-v
		;;
	-q|--quiet) quiet=-q
		;;
	-o|--options)
		shift
		eval `echo $1 | sed 's/,/;/g'`
		Verbose "Applied command-line override options: $1"
		;;
	--) shift; break
		;;
	*) Fatal "Unrecognized option: $1"
		;;
	esac
	shift
done

Verbose "Working directory '$work_dir'"
