export LC_ALL=C LANG=C LANGUAGE=C

# Global fallback variables: very crude defaults. These ones can be
# overriden in multiple places.
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,d,V,h -l work:,options:,verbose,quiet,debug,version,help -- $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
[ -f $profile_dir/config ] || Fatal "File \`$profile_dir/config' not found"
. $profile_dir/config 


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

while :; do
	case "$1" in
	-w|--work) shift
		;;
	-v|--verbose) verbose=-v
		;;
	-q|--quiet) quiet=-q
		;;
	-d|--debug) debug=-d
		;;
	-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'"

# Fix non-null values to predefined ones
# Also export them further when they're set by -oflag=value 
[ -z "$verbose" -o "$verbose" = "-v" ] || export verbose=-v
[ -z "$quiet" -o "$quiet" = "-q" ] || export quiet=-q
[ -z "$debug" -o "$debug" = "-d" ] || export debug=-d

true
