#!/usr/bin/env sh
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
CFG_LOC="${XDG_CONFIG_HOME:-$HOME/.config}/sxhkhm.ini"

### START OF CODE GENERATED BY Argbash v2.9.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
# Generated online by https://argbash.io/generate

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

# THE DEFAULTS INITIALIZATION - OPTIONALS
if [ -s ${CFG_LOC} ] ; then
    source ${CFG_LOC}
    _arg_opt_args="${opt_args}"
    _arg_menuhelper="${menuhelper}"
else
    _arg_opt_args='-dmenu'
    _arg_menuhelper="rofi"
fi


print_help()
{
	printf '%s\n' "loads the output of hkhelper into a user defined helper along with custom options from configuration"
	printf 'Usage: %s [-o|--opt-args <arg>] [-m|--menuhelper <arg>] [-v|--version] [-h|--help]\n' "$0"
	printf '\t%s\n' "-o, --opt-args: optional arguments to pass along to the menuhelper (default: '$_arg_opt_args')"
	printf '\t%s\n' "-m, --menuhelper: menu helper to load [rofi,fzf,dmenu] (default: '$_arg_menuhelper')"
	printf '\t%s\n' "-v, --version: Prints version"
	printf '\t%s\n' "-h, --help: Prints help"
}


parse_commandline()
{
	while test $# -gt 0
	do
		_key="$1"
		case "$_key" in
			-o|--opt-args)
				test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
				_arg_opt_args="$2"
				shift
				;;
			--opt-args=*)
				_arg_opt_args="${_key##--opt-args=}"
				;;
			-o*)
				_arg_opt_args="${_key##-o}"
				;;
			-m|--menuhelper)
				test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
				_arg_menuhelper="$2"
				shift
				;;
			--menuhelper=*)
				_arg_menuhelper="${_key##--menuhelper=}"
				;;
			-m*)
				_arg_menuhelper="${_key##-m}"
				;;
			-v|--version)
				echo test v$version
				exit 0
				;;
			-v*)
				echo test v$version
				exit 0
				;;
			-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 "$@"

run_menu()
{
    ${SCRIPT_DIR}/hkhelper.py -e "$(${SCRIPT_DIR}/hkhelper.py -p | eval "${_arg_menuhelper} ${_arg_opt_args}" | grep -Po '(?<=\s\s)(?=\S).*(?=\b\s\s)(?!$)')"
}

run_menu
