#!/usr/bin/env sh

### Script: parsequery
##
## HTTP クエリを解析する。
##
## Metadata:
##
##   id - 87a8adbd-6276-47bb-b575-d9ae07605332
##   author - <qq542vev at https://purl.org/meta/me/>
##   version - 2.0.3
##   date - 2022-10-12
##   since - 2019-05-28
##   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:
##   parsequery [OPTION]... [QUERY]...
##
## Options:
##   -k,     --key-type ignore | underscore | sanitize 
##                               変数名のタイプを指定する
##   -p,     --prefix VARIABLE_NAME 
##                               変数名の接頭辞を指定する
##   -s,     --suffix VARIABLE_NAME 
##                               変数名の接尾辞を指定する
##   -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=parsequery 2.0.3'

. '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]... [QUERY]..." \
		'' 'Options:'

	param keyType -k --key-type init:='ignore' pattern:'ignore | underscore | sanitize' var:'ignore | underscore | sanitize' -- '変数名のタイプを指定する'
	param prefix  -p --prefix   validate:'regex_match "${OPTARG}" "^[0-9A-Za-z_]*$"' var:VARIABLE_NAME -- '変数名の接頭辞を指定する'
	param suffix  -s --suffix   validate:'regex_match "${OPTARG}" "^[0-9A-Za-z_]*$"' var:VARIABLE_NAME -- '変数名の接尾辞を指定する'
	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}"

awkScript=$(
	cat <<-'__EOF__'
	@include "url_encode.awk"
	@include "shell_argument.awk"
	@include "uri_query_parse.awk"

	BEGIN {
		for(i = 1; i < ARGC; i++) {
			count = uri_query_parse(ARGV[i], query)

			for(i = 0; i <= count; i++) {
				name = query[i, "name"]

				if(keyType == "underscore") {
					name = url_encode(name)

					gsub(/_/, "_5F", name)
					gsub(/-/, "_2D", name)
					gsub(/\./, "_2E", name)
					gsub(/~/, "_7E", name)
					gsub(/%/, "_", name)
				} else if(keyType == "sanitize") {
					gsub(/[^0-9A-Za-z_]/, "", name)
				}

				if(name ~ /^[0-9A-Za-z_]*$/) {
					printf("%s=%s\n", prefix name suffix, shell_argument(query[i, "value"]))
				}
			}
		}

		exit
	}
	__EOF__
)

awk \
	-v "keyType=${keyType}" \
	-v "prefix=${prefix}" \
	-v "suffix=${suffix}" \
	-- "${awkScript}" \
	${@+"${@}"}
