#!/usr/bin/env sh

### Script: getregister
##
## 条件に一致するレジスタの値を取得する。
##
## Metadata:
##
##   id - 7257cff2-0136-41a7-bd09-6e56c349b8b2
##   author - <qq542vev at https://purl.org/meta/me/>
##   version - 1.3.3
##   date - 2022-07-13
##   since - 2020-04-20
##   copyright - Copyright (C) 2020-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:
##   getregister [OPTION]... [PATTERN]...
##
## Options:
##   -c,     --config FILE       設定ファイル
##   -E,     --{no-}extended-regexp 
##                               拡張正規表現を使用する
##   -r,     --{no-}row          デコードせず行のまま表示する
##   -h,     --help              このヘルプを表示して終了する
##   -v,     --version           バージョン情報を表示して終了する
##
## Exit Status:
##     0 - successful termination
##     1 - empty result
##    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=getregister 1.3.3'

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

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

	param config     -c --config               init:'config="${HOME}/.w3mplus/register"' var:FILE -- '設定ファイル'
	flag  regexpFlag -E --{no-}extended-regexp init:@no -- '拡張正規表現を使用する'
	flag  rowFlag    -r --{no-}row             init:@no -- 'デコードせず行のまま表示する'
	disp  :usage     -h --help    -- 'このヘルプを表示して終了する'
	disp  VERSION    -v --version -- 'バージョン情報を表示して終了する'

	msg -- '' 'Exit Status:' \
		'    0 - successful termination' \
		'    1 - empty result' \
		'   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')
	cat -- "${config}"
	exit
esac

awkScript=$(
	cat <<-'__EOF__'
	@include "backslash_unescape.awk"

	BEGIN {
		FS = "\t"

		for(i = 1; i <= ARGC; i++) {
			pattern = ARGV[i]

			while(0 < (getline < config)) {
				key = backslash_unescape($1)

				if((regexpFlag && key ~ pattern) || (!regexpFlag && key == pattern)) {
					if(rowFlag) {
						printf("%s\n", $0)
					} else {
						printf("%s", backslash_unescape($2))
					}

					exit
				}
			}

			close(config)
		}

		exit 1
	}
	__EOF__
)

awkv_escape 'config' "${config}"

awk \
	-v "config=${config}" \
	-v "regexpFlag=${regexpFlag}" \
	-v "rowFlag=${rowFlag}" \
	-- "${awkScript}" ${@+"${@}"} \
|| end_call "${?}"
