#!/usr/bin/env sh

### Script: pushuri
##
## URI を記録する。
##
## Metadata:
##
##   id - c5583088-738d-408e-9f37-c696a5d6d90a
##   author - <qq542vev at https://purl.org/meta/me/>
##   version - 4.0.2
##   date - 2022-12-10
##   since - 2019-08-02
##   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:
##   pushuri [OPTION]... [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 に対応する行番号を指定する
##   -s,     --size UNSIGNED_INTEGER 
##                               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=pushuri 4.0.2'

. 'initialize.sh'
. 'option_error.sh'
. 'regex_match.sh'

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

	param config  -c --config  init:'config="${HOME}/.w3mplus/tabrestore"' 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 に対応する行番号を指定する'
	param size    -s --size    init:='50000' validate:'regex_match "${OPTARG}" "^(0|[1-9][0-9]*)$"' var:UNSIGNED_INTEGER -- '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}"

tmpDir=$(mktemp -d)
unixtime=$(date -u -- '+%Y%m%d%H%M%S' | TZ='UTC+0' utconv)
awkScript=$(
	cat <<-'__EOF__'
	@include "array_print.awk"

	BEGIN {
		previousCount = split("", previous)
	}

	$1 != previous[1] && previous[1] != "" {
		printf("%s\n", array_print(previous, 1, previousCount, "\t"))
	}

	{
		previousCount = split($0, previous)
	}

	END {
		printf("%s\n", array_print(previous, 1, previousCount, "\t"))
	}
	__EOF__
)

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

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

{
	cat -- "${config}"

	for uri in ${@+"${@}"}; do
		i=$((${i-0} + 1))

		eval "colmun=\${c${i}:-1}"
		eval "line=\${l${i}:-1}"

		printf '%s\t%d\t%d\t%s\n' "${uri}" "${line}" "${colmun}" "${unixtime}"
	done
} | awk -- "${awkScript}" | tail -n "${size}" >"${tmpDir}/file"

cat -- "${tmpDir}/file" >"${config}"
