#!/usr/bin/env sh

### Script: setquickmark
##
## クイックマークを登録する。
##
## Metadata:
##
##   id - 435aa761-cbac-4614-9d14-84962f131d16
##   author - <qq542vev at https://purl.org/meta/me/>
##   version - 2.0.3
##   date - 2022-12-10
##   since - 2019-07-29
##   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:
##   setquickmark [OPTION]... [KEY] [URI]...
##
## Options:
##   -c,     --config FILE       設定ファイルを指定する
##           --c1, --c2, --c3, --c4, --c5, --c6, --c7, --c8, --c9 [-]COLUMN_NUMBER 
##                               n個目の URI に対応する列番号を指定する
##           --l1, --l2, --l3, --l4, --l5, --l6, --l7, --l8, --l9 [-]LINE_NUMBER 
##                               n個目の URI に対応する行番号を指定する
##   -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=setquickmark 2.0.3'

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

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

	param config  -c --config  init:'config="${HOME}/.w3mplus/quickmark"' var:FILE -- '設定ファイルを指定する'
	param :'eval "${1#--}=\"\${OPTARG}\""' --c1 --c2 --c3 --c4 --c5 --c6 --c7 --c8 --c9 validate:'regex_match "${OPTARG}" "^-?[1-9][0-9]*$"' var:'[-]COLUMN_NUMBER' -- 'n個目の URI に対応する列番号を指定する'
	param :'eval "${1#--}=\"\${OPTARG}\""' --l1 --l2 --l3 --l4 --l5 --l6 --l7 --l8 --l9 validate:'regex_match "${OPTARG}" "^-?[1-9][0-9]*$"' var:'[-]LINE_NUMBER' -- 'n個目の URI に対応する行番号を指定する'
	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

org_lc uricheck --field '' --verbose -- ${@+"${@}"} || end_call "${EX_USAGE}"

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}"
		;;
	*)
		keyEscape=$(
			cat <<-'__EOF__'
			@include "backslash_escape.awk"

			BEGIN {
				printf("%s", backslash_escape(key))
			}
			__EOF__
		)
		key=$(awk -v "key=${key}" -- "${keyEscape}")
		date=$(date -u -- '+%Y-%m-%dT%H:%M:%SZ')

		cat -- "${config}"

		for uri in ${@+"${@}"}; do
			i=$((${i-0} + 1))
			eval "line=\"\${l${i}-1}\""
			eval "colmun=\"\${c${i}-1}\""

			printf \
				'%s\t%s\t%s\t%s\t%s\n' \
				"${key}" "${uri}" \
				"${line}" "${colmun}" "${date}"
		done | tee "${tmpDir}/add"
		;;
esac | sort -k '1,1' -k '3,3' -t "${CHAR_HT}" -o "${config}"

awkScript=$(
	cat <<-'__EOF__'
	BEGIN {
		FS = "\t"
	}

	{
		printf(" * %s\n", $2)
	}
	__EOF__
)

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

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

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