#!/bin/bash
#
# ARG_OPTIONAL_SINGLE([directory],[d],[path to xanity experiment root])
# ARG_POSITIONAL_SINGLE([action],[accepted actions are init|setup|run|anal|analyze|analyse])
# ARG_HELP([xanity is a tool to manage scientific experiments, their parameters, data, and analysis])
# ARG_VERSION([echo $(pip show -V xanity)])
# ARG_LEFTOVERS([])
# ARGBASH_GO()
# needed because of Argbash --> m4_ignore([

### START OF CODE GENERATED BY Argbash v2.6.1 one line above ###
# Argbash is a bash code generator used to get arguments parsing right.
# Argbash is FREE SOFTWARE, see https://argbash.io for more info
# Generated online by https://argbash.io/generate

# When called, the process ends.
# Args:
# 	$1: The exit message (print to stderr)
# 	$2: The exit code (default is 1)
# if env var _PRINT_HELP is set to 'yes', the usage is print to stderr (prior to )
# Example:
# 	test -f "$_arg_infile" || _PRINT_HELP=yes die "Can't continue, have to supply file as an argument, got '$_arg_infile'" 4
die()
{
	local _ret=$2
	test -n "$_ret" || _ret=1
	test "$_PRINT_HELP" = yes && print_help >&2
	echo "$1" >&2
	exit ${_ret}
}

# Function that evaluates whether a value passed to it begins by a character
# that is a short option of an argument the script knows about.
# This is required in order to support getopts-like short options grouping.
begins_with_short_option()
{
	local first_option all_short_options
	all_short_options='dhv'
	first_option="${1:0:1}"
	test "$all_short_options" = "${all_short_options/$first_option/}" && return 1 || return 0
}



# THE DEFAULTS INITIALIZATION - POSITIONALS
# The positional args array has to be reset before the parsing, because it may already be defined
# - for example if this script is sourced by an argbash-powered script.
_positionals=()
_arg_leftovers=()
# THE DEFAULTS INITIALIZATION - OPTIONALS
_arg_directory=""

# Function that prints general usage of the script.
# This is useful if users asks for it, or if there is an argument parsing error (unexpected / spurious arguments)
# and it makes sense to remind the user how the script is supposed to be called.
print_help ()
{
	printf '%s\n' "xanity is a tool to manage scientific experiments, their parameters, data, and analysis"
	printf 'Usage: %s [-d|--directory <arg>] [-h|--help] [-v|--version] <action> ... \n' "$0"
	printf '\t%s\n' "<action>: accepted actions are init|setup|run|anal|analyze|analyse"
	printf '\t%s\n' "-d,--directory: path to xanity experiment root (optional)"
	printf '\t%s\n' "-h,--help: Prints help"
	printf '\t%s\n' "-v,--version: Prints version"
}

# The parsing of the command-line
parse_commandline ()
{
	while test $# -gt 0
	do
		_key="$1"
		case "$_key" in
			# We support whitespace as a delimiter between option argument and its value.
			# Therefore, we expect the --directory or -d value.
			# so we watch for --directory and -d.
			# Since we know that we got the long or short option,
			# we just reach out for the next argument to get the value.
			-d|--directory)
				test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
				_arg_directory="$2"
				shift
				;;
			# We support the = as a delimiter between option argument and its value.
			# Therefore, we expect --directory=value, so we watch for --directory=*
			# For whatever we get, we strip '--directory=' using the ${var##--directory=} notation
			# to get the argument value
			--directory=*)
				_arg_directory="${_key##--directory=}"
				;;
			# We support getopts-style short arguments grouping,
			# so as -d accepts value, we allow it to be appended to it, so we watch for -d*
			# and we strip the leading -d from the argument string using the ${var##-d} notation.
			-d*)
				_arg_directory="${_key##-d}"
				;;
			# The help argurment doesn't accept a value,
			# we expect the --help or -h, so we watch for them.
			-h|--help)
				print_help
				exit 0
				;;
			# We support getopts-style short arguments clustering,
			# so as -h doesn't accept value, other short options may be appended to it, so we watch for -h*.
			# After stripping the leading -h from the argument, we have to make sure
			# that the first character that follows coresponds to a short option.
			-h*)
				print_help
				exit 0
				;;
			# See the comment of option '--help' to see what's going on here - principle is the same.
			-v|--version)
				echo "$(pip show -V xanity)"
				exit 0
				;;
			# See the comment of option '-h' to see what's going on here - principle is the same.
			-v*)
				echo "$(pip show -V xanity)"
				exit 0
				;;
			*)
				_positionals+=("$1")
				;;
		esac
		shift
	done
}


# Check that we receive expected amount positional arguments.
# Return 0 if everything is OK, 1 if we have too little arguments
# and 2 if we have too much arguments
handle_passed_args_count ()
{
	_required_args_string="'action'"
	test ${#_positionals[@]} -ge 1 || _PRINT_HELP=yes die "FATAL ERROR: Not enough positional arguments - we require at least 1 (namely: $_required_args_string), but got only ${#_positionals[@]}." 1
# We accept up to inifinitely many positional values, so
# there is no need to check for spurious positional arguments.
}

# Take arguments that we have received, and save them in variables of given names.
# The 'eval' command is needed as the name of target variable is saved into another variable.
assign_positional_args ()
{
	# We have an array of variables to which we want to save positional args values.
	# This array is able to hold array elements as targets.
	_positional_names=('_arg_action' )
	# If we allow up to infinitely many args, we calculate how many of values
	# were actually passed, and we extend the target array accordingly.
	_our_args=$((${#_positionals[@]} - ${#_positional_names[@]}))
	for ((ii = 0; ii < _our_args; ii++))
	do
		_positional_names+=("_arg_leftovers[$((ii + 0))]")
	done

	for (( ii = 0; ii < ${#_positionals[@]}; ii++))
	do
		eval "${_positional_names[ii]}=\${_positionals[ii]}" || die "Error during argument parsing, possibly an Argbash bug." 1
	done
}

# Now call all the functions defined above that are needed to get the job done
parse_commandline "$@"
handle_passed_args_count
assign_positional_args

# OTHER STUFF GENERATED BY Argbash

### END OF CODE GENERATED BY Argbash (sortof) ### ])
# [ <-- needed because of Argbash


#dir_exist="$( [[ -d ${_arg_directory} ]] )"
#dir_isxanity="$( [[ -d ${_arg_directory}/.xanity ]] )"
#dircheck() { [[ $dir_exist ]] || { printf '%s does not appear to exist' "$_arg_directory"; exit 1; }; }
#xancheck() { [[ $dir_isxanity ]] || { printf '%s is not a valid xanity project' "$_arg_directory"; exit 1; }; }
#xanity_check() { dircheck; xancheck; }

dircheck_push() { [[ -n "$_arg_directory" && -d "$_arg_directory" ]] && pushd "$_arg_directory"; }

dircheck_push
case "$_arg_action" in

    "init")
        python -m xanity init "$_arg_leftovers"
    	  ;;

    "setup")
      	python -m xanity setup "$_arg_leftovers"
    	  ;;

    "run"|"process")
        bash xanity-run.sh run "$_arg_leftovers"
        ;;

    "anal"|"analyze"|"analyse")
        bash xanity-run.sh analyze "$_arg_leftovers"
        ;;

	*)
		echo "did not recognize that xanity command"
		exit 1

esac

popd 2> /dev/null
exit 0

# ] <-- needed because of Argbash
