#!/usr/bin/env sh

### Script: setusercommand
##
## ユーザーコマンドを登録する。
##
## Metadata:
##
##   id - bc9554d8-7a8a-4e78-91f2-4aa37f12a21e
##   author - <qq542vev at https://purl.org/meta/me/>
##   version - 1.2.1
##   date - 2022-12-10
##   since - 2019-12-15
##   copyright - Copyright (C) 2019-2022 qq542vev. Some rights reserved.
##   license - <CC-BY at https://creativecommons.org/licenses/by/4.0/>
##   package - w3mplus
##
## See Also:
##
##   * <Project homepage at https://github.com/qq542vev/w3mplus>
##   * <Bug report at https://github.com/qq542vev/w3mplus/issues>
##
## Help Output:
##
## ------ Text ------
## Usage:
##   setusercommand [OPTION]... [CALL] [COMMAND_ARG]...
##
## Options:
##   -c,     --config FILE       設定ファイルを指定する
##   -h,     --help              このヘルプを表示して終了する
##   -v,     --version           バージョン情報を表示して終了する
##
## Exit Status:
##     0 - successful termination
##    64 - command line usage error
##    65 - data format error
##    66 - cannot open input
##    67 - addressee unknown
##    68 - host name unknown
##    69 - service unavailable
##    70 - internal software error
##    71 - system error (e.g., can't fork)
##    72 - critical OS file missing
##    73 - can't create (user) output file
##    74 - input/output error
##    75 - temp failure; user is invited to retry
##    76 - remote error in protocol
##    77 - permission denied
##    78 - configuration error
##   129 - received SIGHUP
##   130 - received SIGINT
##   131 - received SIGQUIT
##   143 - received SIGTERM
## ------------------

readonly 'VERSION=setusercommand 1.2.1'

. 'initialize.sh'
. 'option_error.sh'
. 'awkv_escape.sh'
. 'control_character.sh'

output() {
	awk -F '\t' -- '{
		call = $1
		command = $2
		date = $3

		if(NR != 1) {
			printf("\n")
		}

		printf("call type: %s\n", call)
		printf("check command: %s\n", command)
		printf("date: %s\n", date)
	}'
}

# @getoptions
parser_definition() {
	setup REST abbr:true error:option_error plus:true no:0 help:usage \
		-- 'Usage:' "  ${2##*/} [OPTION]... [CALL] [COMMAND_ARG]..." \
		'' 'Options:'

	param config  -c --config  init:'config="${HOME}/.w3mplus/usercommand"' var:FILE -- '設定ファイルを指定する'
	disp  :usage  -h --help    -- 'このヘルプを表示して終了する'
	disp  VERSION -v --version -- 'バージョン情報を表示して終了する'

	msg -- '' 'Exit Status:' \
		'    0 - successful termination' \
		'   64 - command line usage error' \
		'   65 - data format error' \
		'   66 - cannot open input' \
		'   67 - addressee unknown' \
		'   68 - host name unknown' \
		'   69 - service unavailable' \
		'   70 - internal software error' \
		"   71 - system error (e.g., can't fork)" \
		'   72 - critical OS file missing' \
		"   73 - can't create (user) output file" \
		'   74 - input/output error' \
		'   75 - temp failure; user is invited to retry' \
		'   76 - remote error in protocol' \
		'   77 - permission denied' \
		'   78 - configuration error' \
		'  129 - received SIGHUP' \
		'  130 - received SIGINT' \
		'  131 - received SIGQUIT' \
		'  143 - received SIGTERM'
}
# @end

# @gengetoptions parser -i parser_definition parse "${1}"
# @end

eval "$(getoptions parser_definition parse "${0}")"
parse ${@+"${@}"}
eval "set -- ${REST}"

if [ '!' -e "${config}" ]; then
	configDir=$(dirname -- "${config}"; printf '_')
	mkdir -p -- "${configDir%?_}"

	: >"${config}"
fi

if [ '!' -f "${config}" ]; then
	printf "%s: '%s' は通常ファイルではありません。\\n" "${0##*/}" "${config}" >&2
	printf "詳細については '%s' を実行してください。\\n" "${0##*/} --help" >&2

	end_call "${EX_DATAERR}"
elif [ '!' -r "${config}" ]; then
	printf "%s: '%s' の読み込み許可がありません。\\n" "${0##*/}" "${config}" >&2
	printf "詳細については '%s' を実行してください。\\n" "${0##*/} --help" >&2

	end_call "${EX_NOINPUT}"
fi

case "${#}" in '0')
	org_lc sh -c "${VISUAL:-${EDITOR:-vi --}} \"\${1}\"" 'sh' "${config}"
	exit
esac

awkv_escape 'key' "${1}"
shift

awkv_escape 'command' "${*}"
tmpDir="$(mktemp -d)"

case "${#}" in
	'0')
		awkScript=$(
			cat <<-'__EOF__'
			@include "backslash_escape.awk"

			BEGIN {
				FS = "\t"
				esKey = backslash_escape(key)
			}

			{
				if($1 == esKey) {
					printf("%s\n", $0) >>del
				} else {
					printf("%s\n", $0)
				}
			}
			__EOF__
		)
		awkv_escape 'del' "${tmpDir}/del"

		awk \
			-v "key=${key}" -v "del=${del}" \
			-- "${awkScript}" "${config}"
		;;
	*)
		awkScript=$(
			cat <<-'__EOF__'
			@include "backslash_escape.awk"

			BEGIN {
				FS = "\t"
				esKey = backslash_escape(key)
				esCommand = backslash_escape(command)
			}

			$1 != esKey || $2 != esCommand {
				printf("%s\n", $0)
			}

			END {
				printf("%s\t%s\t%s\n", esKey, esCommand, date)
				printf("%s\t%s\t%s\n", esKey, esCommand, date) >>add
			}
			__EOF__
		)
		awkv_escape 'add' "${tmpDir}/add"

		awk \
			-v "key=${key}" -v "command=${command}" \
			-v "date=$(date -u -- '+%Y-%m-%dT%H:%M:%SZ')" -v "add=${add}" \
			-- "${awkScript}" "${config}"
		;;
esac | sort -k '1,1' -k '3,3' -t "${CHAR_HT}" -o "${config}"

awkScript=$(
	cat <<-'__EOF__'

	BEGIN {
		FS = "\t"
	}

	{
		call = $1
		command = $2
		date = $3

		if(NR != 1) {
			printf("\n")
		}

		printf("call type: %s\n", call)
		printf("check command: %s\n", command)
		printf("date: %s\n", date)
	}
	__EOF__
)

if [ -s "${tmpDir}/del" ]; then
	printf 'Deleted user command\n\n'

	awk -- "${awkScript}" "${tmpDir}/del"
elif [ -s "${tmpDir}/add" ]; then
	printf 'Added user command\n\n'

	awk -- "${awkScript}" "${tmpDir}/add"
fi
