#!/usr/bin/env sh


readonly 'VERSION=w3mcookieconfig 2.0.4'



set -efu
umask '0022'
readonly "LC_ALL_ORG=${LC_ALL-}"
LC_ALL='C'
IFS=$(printf ' \t\n_')
IFS="${IFS%_}"
PATH="${PATH-}${PATH:+:}$(command -p getconf 'PATH')"
UNIX_STD='2003'         # HP-UX POSIX mode
XPG_SUS_ENV='ON'        # AIX POSIX mode
XPG_UNIX98='OFF'        # AIX UNIX 03 mode
POSIXLY_CORRECT='1'     # GNU Coreutils POSIX mode
COMMAND_MODE='unix2003' # macOS UNIX 03 mode
export 'LC_ALL' 'IFS' 'PATH' 'UNIX_STD' 'XPG_SUS_ENV' 'XPG_UNIX98' 'POSIXLY_CORRECT' 'COMMAND_MODE'




readonly 'EX_OK=0' # successful termination

readonly 'EX__BASE=64' # base value for error messages

readonly 'EX_USAGE=64'       # command line usage error
readonly 'EX_DATAERR=65'     # data format error
readonly 'EX_NOINPUT=66'     # cannot open input
readonly 'EX_NOUSER=67'      # addressee unknown
readonly 'EX_NOHOST=68'      # host name unknown
readonly 'EX_UNAVAILABLE=69' # service unavailable
readonly 'EX_SOFTWARE=70'    # internal software error
readonly 'EX_OSERR=71'       # system error (e.g., can't fork)
readonly 'EX_OSFILE=72'      # critical OS file missing
readonly 'EX_CANTCREAT=73'   # can't create (user) output file
readonly 'EX_IOERR=74'       # input/output error
readonly 'EX_TEMPFAIL=75'    # temp failure; user is invited to retry
readonly 'EX_PROTOCOL=76'    # remote error in protocol
readonly 'EX_NOPERM=77'      # permission denied
readonly 'EX_CONFIG=78'      # configuration error

readonly 'EX__MAX=78' # maximum listed value

trap 'case "${?}" in 0) end_call;; *) end_call "${EX_SOFTWARE}";; esac' 0 # EXIT
trap 'end_call 129' 1                                                     # SIGHUP
trap 'end_call 130' 2                                                     # SIGINT
trap 'end_call 131' 3                                                     # SIGQUIT
trap 'end_call 143' 15                                                    # SIGTERM

alias org_lc='LC_ALL="${LC_ALL_ORG}"'


end_call() {
	trap '' 0 # EXIT
	rm -fr -- ${tmpDir:+"${tmpDir}"}
	exit "${1:-0}"
}



option_error() {
	printf '%s: %s\n' "${0##*/}" "${1}" >&2
	printf "詳細については '%s' を実行してください。\\n" "${0##*/} --help" >&2

	end_call "${EX_USAGE}"
}



regex_match() {
	awk -- '
		BEGIN {
			for(i = 2; i < ARGC; i++) {
				if(ARGV[1] !~ ARGV[i]) {
					exit 1
				}
			}

			exit
		}
	' ${@+"${@}"} || return 1

	return 0
}



append_array_posix() {
	while [ 2 -le "${#}" ]; do
		__append_array_posix "${1}" "${2}"

		eval "shift 2; set -- '${1}'" '${@+"${@}"}'
	done
}


__append_array_posix() {
	set "${1}" "${2-}" ''

	until [ "${2#*\'}" '=' "${2}" ]; do
		set -- "${1}" "${2#*\'}" "${3}${2%%\'*}'\"'\"'"
	done

	eval "${1}=\"\${${1}-}\${${1}:+ }'\${3}\${2}'\""
}

validation_param() {
	awk -- '



function domain_check(domain) {
	return domain ~ /^[0-9A-Za-z]([0-9A-Za-z-]*[0-9A-Za-z])?(\.[0-9A-Za-z]([0-9A-Za-z-]*[0-9A-Za-z])?)+$/
}

		BEGIN {
			split(ARGV[1], value, "=")
			exit !((value[1] == "add" | value[1] == "delete" || value[1] == "toggle") && domain_check(value[2]))
		}
	' "${1}"
}

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

	param :'append_array_posix accept "accept-${OPTARG}"' -a --accept validate:'validation_param "${OPTARG}"' var:'add=DOMAIN | reject=DOMAIN | toggle=DOMAIN' -- 'cookie_accept_domains に DOMAIN をセットする'
	flag accept --no-accept init:@no on: no: -- '-a, --accept をリセットする'
	flag placeFlag -i --{no-}in-place init:@no -- 'FILE を更新して保存する'
	param :'append_array_posix reject "reject-${OPTARG}"' -r --reject validate:'validation_param "${OPTARG}"' var:'add=DOMAIN | reject=DOMAIN | toggle=DOMAIN' -- 'cookie_reject_domains に DOMAIN をセットする'
	flag reject --no-reject init:@no on: no: -- '-r, --reject をリセットする'
	flag subdomain -s --{no-}subdomain init:@no -- 'サブドメインを有効にする'
	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'
}

accept=''
placeFlag='0'
reject=''
subdomain='0'
REST=''
parse() {
	OPTIND=$(($# + 1))
	while OPTARG= && [ $# -gt 0 ]; do
		set -- "${1%%\=*}" "${1#*\=}" "$@"
		while [ ${#1} -gt 2 ]; do
			case $1 in *[!a-zA-Z0-9_-]*) break ;; esac
			case '--accept' in
			"$1")
				OPTARG=
				break
				;;
			$1*) OPTARG="$OPTARG --accept" ;;
			esac
			case '--no-accept' in
			"$1")
				OPTARG=
				break
				;;
			$1*) OPTARG="$OPTARG --no-accept" ;;
			esac
			case '--in-place' in
			"$1")
				OPTARG=
				break
				;;
			$1*) OPTARG="$OPTARG --in-place" ;;
			esac
			case '--no-in-place' in
			"$1")
				OPTARG=
				break
				;;
			$1*) OPTARG="$OPTARG --no-in-place" ;;
			esac
			case '--reject' in
			"$1")
				OPTARG=
				break
				;;
			$1*) OPTARG="$OPTARG --reject" ;;
			esac
			case '--no-reject' in
			"$1")
				OPTARG=
				break
				;;
			$1*) OPTARG="$OPTARG --no-reject" ;;
			esac
			case '--subdomain' in
			"$1")
				OPTARG=
				break
				;;
			$1*) OPTARG="$OPTARG --subdomain" ;;
			esac
			case '--no-subdomain' in
			"$1")
				OPTARG=
				break
				;;
			$1*) OPTARG="$OPTARG --no-subdomain" ;;
			esac
			case '--help' in
			"$1")
				OPTARG=
				break
				;;
			$1*) OPTARG="$OPTARG --help" ;;
			esac
			case '--version' in
			"$1")
				OPTARG=
				break
				;;
			$1*) OPTARG="$OPTARG --version" ;;
			esac
			break
		done
		case ${OPTARG# } in
		*\ *)
			eval "set -- $OPTARG $1 $OPTARG"
			OPTIND=$((($# + 1) / 2)) OPTARG=$1
			shift
			while [ $# -gt "$OPTIND" ]; do
				OPTARG="$OPTARG, $1"
				shift
			done
			set "Ambiguous option: $1 (could be $OPTARG)" ambiguous "$@"
			option_error "$@" >&2 || exit $?
			echo "$1" >&2
			exit 1
			;;
		?*)
			[ "$2" = "$3" ] || OPTARG="$OPTARG=$2"
			shift 3
			eval 'set -- "${OPTARG# }"' ${1+'"$@"'}
			OPTARG=
			;;
		*) shift 2 ;;
		esac
		case $1 in
		--?*=*)
			OPTARG=$1
			shift
			eval 'set -- "${OPTARG%%\=*}" "${OPTARG#*\=}"' ${1+'"$@"'}
			;;
		--no-* | --without-*) unset OPTARG ;;
		-[ar]?*)
			OPTARG=$1
			shift
			eval 'set -- "${OPTARG%"${OPTARG#??}"}" "${OPTARG#??}"' ${1+'"$@"'}
			;;
		-[ishv]?*)
			OPTARG=$1
			shift
			eval 'set -- "${OPTARG%"${OPTARG#??}"}" -"${OPTARG#??}"' ${1+'"$@"'}
			OPTARG=
			;;
		+*) unset OPTARG ;;
		esac
		case $1 in
		'-a' | '--accept')
			[ $# -le 1 ] && set "required" "$1" && break
			OPTARG=$2
			validation_param "${OPTARG}" || {
				set -- validation_param:$? "$1" validation_param "${OPTARG}"
				break
			}
			append_array_posix accept "accept-${OPTARG}"
			shift
			;;
		'--no-accept')
			[ "${OPTARG:-}" ] && OPTARG=${OPTARG#*\=} && set "noarg" "$1" && break
			eval '[ ${OPTARG+x} ] &&:' && OPTARG='' || OPTARG=''
			accept="$OPTARG"
			;;
		'-i' | '--in-place' | '--no-in-place')
			[ "${OPTARG:-}" ] && OPTARG=${OPTARG#*\=} && set "noarg" "$1" && break
			eval '[ ${OPTARG+x} ] &&:' && OPTARG='1' || OPTARG='0'
			placeFlag="$OPTARG"
			;;
		'-r' | '--reject')
			[ $# -le 1 ] && set "required" "$1" && break
			OPTARG=$2
			validation_param "${OPTARG}" || {
				set -- validation_param:$? "$1" validation_param "${OPTARG}"
				break
			}
			append_array_posix reject "reject-${OPTARG}"
			shift
			;;
		'--no-reject')
			[ "${OPTARG:-}" ] && OPTARG=${OPTARG#*\=} && set "noarg" "$1" && break
			eval '[ ${OPTARG+x} ] &&:' && OPTARG='' || OPTARG=''
			reject="$OPTARG"
			;;
		'-s' | '--subdomain' | '--no-subdomain')
			[ "${OPTARG:-}" ] && OPTARG=${OPTARG#*\=} && set "noarg" "$1" && break
			eval '[ ${OPTARG+x} ] &&:' && OPTARG='1' || OPTARG='0'
			subdomain="$OPTARG"
			;;
		'-h' | '--help')
			usage
			exit 0
			;;
		'-v' | '--version')
			echo "${VERSION}"
			exit 0
			;;
		--)
			shift
			while [ $# -gt 0 ]; do
				REST="${REST} \"\${$((OPTIND - $#))}\""
				shift
			done
			break
			;;
		[-+]?*)
			set "unknown" "$1"
			break
			;;
		*)
			REST="${REST} \"\${$((OPTIND - $#))}\""
			;;
		esac
		shift
	done
	[ $# -eq 0 ] && {
		OPTIND=1
		unset OPTARG
		return 0
	}
	case $1 in
	unknown) set "Unrecognized option: $2" "$@" ;;
	noarg) set "Does not allow an argument: $2" "$@" ;;
	required) set "Requires an argument: $2" "$@" ;;
	pattern:*) set "Does not match the pattern (${1#*:}): $2" "$@" ;;
	notcmd) set "Not a command: $2" "$@" ;;
	*) set "Validation error ($1): $2" "$@" ;;
	esac
	option_error "$@" >&2 || exit $?
	echo "$1" >&2
	exit 1
}
usage() {
	cat <<'GETOPTIONSHERE'
Usage:
  w3mcookieconfig [OPTION]... [FILE]...

Options:
  -a,     --accept add=DOMAIN | reject=DOMAIN | toggle=DOMAIN 
                              cookie_accept_domains に DOMAIN をセットする
          --no-accept         -a, --accept をリセットする
  -i,     --{no-}in-place     FILE を更新して保存する
  -r,     --reject add=DOMAIN | reject=DOMAIN | toggle=DOMAIN 
                              cookie_reject_domains に DOMAIN をセットする
          --no-reject         -r, --reject をリセットする
  -s,     --{no-}subdomain    サブドメインを有効にする
  -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
GETOPTIONSHERE
}

parse ${@+"${@}"}
eval "set -- ${REST}"

tmpDir=$(mktemp -d)
tmpConfig="${tmpDir}/config"
awkScript=$(
	cat <<-'__EOF__'



		function regex_escape(string, type) {
			if(type == "" || type == "BRE") {
				gsub(/[].\\*[^$]/, "\\\\&", string)
			} else if(type == "ERE") {
				gsub(/[].\\*+?|(){}[^$]/, "\\\\&", string)
			}

			return string
		}

			BEGIN {
				split("", key)
				count = split("", value)

				key["cookie_accept_domains"] = "accept"
				key["cookie_reject_domains"] = "reject"

				for(i = 1; i < ARGC; i++) {
					if(ARGV[i] == "--") {
							delete ARGV[i]
							break
					}

					position = index(ARGV[i], "=")

					count++
					value[count, "type"] = substr(ARGV[i], 1, position - 1)
					value[count, "uri"] = (subdomain ? "." : "") substr(ARGV[i], position + 1)

					delete ARGV[i]
				}
			}

			$1 in key {
				name = key[$1]

				for(i = 1; i <= count; i++) {
					escaped = regex_escape(value[i, "uri"], "ERE")
					flag = $2 ~ "(^|,)" escaped "(,|$)"

					if((value[i, "type"] ==  name "-add" || value[i, "type"] == name "-toggle") && !flag) {
						$2 = $2 ($2 == "" ? "" : ",") value[i, "uri"]
					} else if((value[i, "type"] == name "-delete" || value[i, "type"] == name "-toggle") && flag) {
						gsub("(^|,)" escaped "(,|$)", "", $2)
					}
				}

				printf("%s %s\n", $1, $2)

				next
			}

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

command='awk -v "subdomain=${subdomain}" -- "${awkScript}"'" ${accept} ${reject} --"

case "${placeFlag}" in
'0') eval "${command}" '${@+"${@}"}' ;;
*)
	for config in ${@+"${@}"}; do
		case "${config}" in '-')
			printf "%s: '-i', '--in-place' オプションでは標準入力は使用できません。無視します。\\n" "${0##*/}" >&2
			continue
			;;
		esac

		eval "${command}" '"${config}"' >"${tmpConfig}"
		cat -- "${tmpConfig}" >"${config}"
	done
	;;
esac
