#!/bin/bash

# shellcheck disable=SC2016
# SC2016: Expressions don't expand in single quotes, use double quotes for that.

version=2.10.0
# ARG_POSITIONAL_INF([input],[The input file to transform],[1])
# ARG_OPTIONAL_SINGLE([output],[o],[Name of the output file (pass '-' for stdout and empty string for the same as input file)],[""])
# ARG_VERSION([echo "argbash-1to2 v$version"])
# ARG_HELP([Convert a template for argbash>=1,<2 to argbash>=2,<3])

# 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='ovh'
	first_option="${1:0:1}"
	test "$all_short_options" = "${all_short_options/$first_option/}" && return 1 || return 0
}

# THE DEFAULTS INITIALIZATION - POSITIONALS
_positionals=()
_arg_input=('' )
# THE DEFAULTS INITIALIZATION - OPTIONALS
_arg_output=""


print_help()
{
	printf '%s\n' "Convert a template for argbash>=1,<2 to argbash>=2,<3"
	printf 'Usage: %s [-o|--output <arg>] [-v|--version] [-h|--help] <input-1> [<input-2>] ... [<input-n>] ...\n' "$0"
	printf '\t%s\n' "<input>: The input file to transform"
	printf '\t%s\n' "-o, --output: Name of the output file (pass '-' for stdout and empty string for the same as input file) (default: '""')"
	printf '\t%s\n' "-v, --version: Prints version"
	printf '\t%s\n' "-h, --help: Prints help"
}


parse_commandline()
{
	_positionals_count=0
	while test $# -gt 0
	do
		_key="$1"
		case "$_key" in
			-o|--output)
				test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
				_arg_output="$2"
				shift
				;;
			--output=*)
				_arg_output="${_key##--output=}"
				;;
			-o*)
				_arg_output="${_key##-o}"
				;;
			-v|--version)
				echo "argbash-1to2 v$version"
				exit 0
				;;
			-v*)
				echo "argbash-1to2 v$version"
				exit 0
				;;
			-h|--help)
				print_help
				exit 0
				;;
			-h*)
				print_help
				exit 0
				;;
			*)
				_last_positional="$1"
				_positionals+=("$_last_positional")
				_positionals_count=$((_positionals_count + 1))
				;;
		esac
		shift
	done
}


handle_passed_args_count()
{
	local _required_args_string="'input'"
	test "${_positionals_count}" -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_count}." 1
}


assign_positional_args()
{
	local _positional_name _shift_for=$1
	_positional_names="_arg_input "
	_our_args=$((${#_positionals[@]} - 1))
	for ((ii = 0; ii < _our_args; ii++))
	do
		_positional_names="$_positional_names _arg_input[$((ii + 1))]"
	done

	shift "$_shift_for"
	for _positional_name in ${_positional_names}
	do
		test $# -gt 0 || break
		eval "$_positional_name=\${1}" || die "Error during argument parsing, possibly an Argbash bug." 1
		shift
	done
}

parse_commandline "$@"
handle_passed_args_count
assign_positional_args 1 "${_positionals[@]}"

# OTHER STUFF GENERATED BY Argbash

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

#

_files_to_clean=()
cleanup()
{
	test "${#_files_to_clean[*]}" != 0 && rm -f "${_files_to_clean[@]}"
}

do_stuff ()
{
	# SCRIPT_DIR is likely also a default, but maybe not - it may have been set explicitly
	grep -q '\${\?SCRIPT_DIR' -- "$infname" && echo "You probably use a variable 'SCRIPT_DIR' in your script. It may be that you should rename it to 'script_dir', but this is not certain :-(" >&2
	# We match $_ARG_FOO as well as ${ARG_FOO...
	# and _ARGS_FOO
	sed 's/\(\${\?_ARGS\?_\w\+\)/\L\1\l/g' "$infname"
}

outfname="$_arg_output"
test "${#infname[@]}" -gt 1 && test -n "$outfname" && die "You have specified more than one (${#infname[@]}) input filenames, so you probably want to modify the corresponding files in-place. In order to do so, you can't specify an output filename, even '-' does make no sense (currently: '$outfname')"

trap cleanup EXIT
for infname in "${_arg_input[@]}"
do
	test -f "$infname" || { echo "The input parameter has to be a file (got: '$infname')" >&2; exit 1; }

	test -n "$_arg_output" || outfname="$infname"
	if test "$outfname" = '-'
	then
		do_stuff
	else
		# vvv This should catch most of the cases when we want to overwrite the source file
		# vvv and we don't want to leave a file (not even an empty one) when something goes wrong.
		temp_outfile="temp_$$"
		_files_to_clean+=("$temp_outfile")
		do_stuff > "$temp_outfile"
		mv "$temp_outfile" "$outfname"
		# So we don't make .m4 scripts executable
		chmod --reference "$infname" "$outfname"
	fi
done

#
# ] <-- needed because of Argbash
