#!/usr/bin/env bash
# Erik Martin-Dorel, 2021 (configure script for SsrMultinomials)
#
# ARG_OPTIONAL_SINGLE([native-compiler],[],[Pre-compiles .coq-native/* files (yes|no)],[])
# ARG_OPTIONAL_SINGLE([prefix],[],[Dummy option (its value is ignored) for Nix compatibility],[])
# ARG_HELP([configure script for SsrMultinomials])
# ARGBASH_GO()
# needed because of Argbash --> m4_ignore([
### START OF CODE GENERATED BY Argbash v2.10.0 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

die()
{
	local _ret="${2:-1}"
	test "${_PRINT_HELP:-no}" = yes && print_help >&2
	echo "$1" >&2
	exit "${_ret}"
}

begins_with_short_option()
{
	local first_option all_short_options='h'
	first_option="${1:0:1}"
	test "$all_short_options" = "${all_short_options/$first_option/}" && return 1 || return 0
}

# THE DEFAULTS INITIALIZATION - OPTIONALS
_arg_native_compiler=
_arg_prefix=

print_help()
{
	printf '%s\n' "configure script for SsrMultinomials"
	printf 'Usage: %s [--native-compiler <arg>] [--prefix <arg>] [-h|--help]\n' "$0"
	printf '\t%s\n' "--native-compiler: Pre-compiles .coq-native/* files (yes|no)"
	printf '\t%s\n' "--prefix: Dummy option (its value is ignored) for Nix compatibility"
	printf '\t%s\n' "-h, --help: Prints help"
}

parse_commandline()
{
	while test $# -gt 0
	do
		_key="$1"
		case "$_key" in
			--native-compiler)
				test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
				_arg_native_compiler="$2"
				shift
				;;
			--native-compiler=*)
				_arg_native_compiler="${_key##--native-compiler=}"
				;;
			--prefix)
				test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
				_arg_prefix="$2"
				shift
				;;
			--prefix=*)
				_arg_prefix="${_key##--prefix=}"
				;;
			-h|--help)
				print_help
				exit 0
				;;
			-h*)
				print_help
				exit 0
				;;
			*)
				_PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1
				;;
		esac
		shift
	done
}

parse_commandline "$@"

# OTHER STUFF GENERATED BY Argbash

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

dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )

coq_native_compiler_default() {
    coqc -config | grep -q 'COQ_NATIVE_COMPILER_DEFAULT=yes'
}

coq_native_compiler() {
    case "$_arg_native_compiler" in
        yes)
            return 0 ;;
        no)
            return 1 ;;
        *)
            coq_native_compiler_default ;;
    esac
}

main() {
    if [ -n "$_arg_prefix" ]; then
        echo "Warning: Ignore argument '--prefix=$_arg_prefix'" >&2
    fi
    if coq_native_compiler; then
        echo 'coq-native support enabled!' >&2
        sed -e 's/;coq-native-disabled; \?//' "$dir/src/dune.in" > "$dir/src/dune"
    else
        echo 'coq-native support disabled.' >&2
        cat "$dir/src/dune.in" > "$dir/src/dune"
    fi
}

main

# ] <-- needed because of Argbash
