#!/usr/bin/env sh

### Script: htmlframe
##
## HTML のフレームページを作成する。
##
## Metadata:
##
##   id - 389e2c50-477c-4e4e-b999-a6459ca96e46
##   author - <qq542vev at https://purl.org/meta/me/>
##   version - 1.2.1
##   date - 2022-12-10
##   since - 2022-06-28
##   copyright - Copyright (C) 2022-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:
##   htmlframe [OPTION]... [URI]...
##
## Options:
##   -a,     --attribute NANE=VALUE 
##                               frameset要素に属性を追加する
##           --no-attribute      -a, --attribute をリセットする
##   -H,     --head ELEMENT      head要素内に ELEMENT を追加する
##           --no-head           -H, --head をリセットする
##   -t,     --title TEXT        フレームページのタイトルを指定する
##   -T,     --template FILE     テンプレートファイルを指定する
##           --n1, --n2, --n3, --n4, --n5, --n6, --n7, --n8, --n9 NAME 
##                               n個目の URI に対応するname属性を指定する
##           --t1, --t2, --t3, --t4, --t5, --t6, --t7, --t8, --t9 TEXT 
##                               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=htmlframe 1.2.1'

. 'initialize.sh'
. 'option_error.sh'
. 'regex_match.sh'
. 'append_array_posix.sh'
. 'append_string.sh'
. 'html_escape.sh'
. 'safe_string.sh'

### Function: html_safetext
##
## HTML での安全な文字列に変換する。
##
## Parameters:
##
##   $1 - 結果を代入する変数名。
##   $2 - 対象の文字列。

html_safetext() {
	eval "${1}=\"\${2}\""
	eval 'safe_string "${1}"' "\"\${${1}}\""
	eval 'html_escape "${1}"' "\"\${${1}}\""
}

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

	param :'append_array_posix attribute "${OPTARG%%=*}" "${OPTARG#*=}"' -a --attribute validate:'regex_match "${OPTARG}" "^[A-Za-z-]+="' var:'NANE=VALUE' -- 'frameset要素に属性を追加する'
	flag  attribute --no-attribute init:@no on: no: -- '-a, --attribute をリセットする'
	param :'append_string "HEAD_CONTENT" "${OPTARG}"' -H --head-content var:ELEMENT -- 'head要素内に ELEMENT を追加する'
	flag  HEAD_CONTENT    --no-head-content init:@no on: no: -- '-H, --head-content をリセットする'
	param :'html_safetext "TITLE" "${OPTARG}"' -t --title init:='No Title' var:TEXT -- 'フレームページのタイトルを指定する'
	param W3MPLUS_TEMPLATE_FRAMESET -T --template init:@none var:FILE -- 'テンプレートファイルを指定する'
	param :'eval "${1#--}=\"\${OPTARG}\""'       --n1 --n2 --n3 --n4 --n5 --n6 --n7 --n8 --n9 validate:'regex_match "${OPTARG}" "^([A-Za-z][0-9A-Za-z\\-_:.]*)?$"' var:NAME -- 'n個目の URI に対応するname属性を指定する'
	param :'html_safetext "${1#--}" "${OPTARG}"' --t1 --t2 --t3 --t4 --t5 --t6 --t7 --t8 --t9 var:TEXT -- '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'

	msg -- '' 'Environment Variables:' \
		'  W3MPLUS_FRAMESET_PROGRAM - HTML フレーム用の呼び出しコマンド'
}
# @end

# @gengetoptions parser -i parser_definition parse "${1}"
# @end

eval "$(getoptions parser_definition parse "${0}")"
parse ${@+"${@}"}
eval "set -- ${REST}"

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

	BEGIN {
		split("", attribute)

		for(i = 1; i < ARGC; i += 2) {
			attribute[ARGV[i]] = ARGV[i + 1]
		}

		for(name in attribute) {
			printf(" %s=\"%s\"", name, html_escape(safe_string(attribute[name])))
		}
	}
	__EOF__
)

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

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

	html_escape 'uri' "${uri}"

	eval "name=\${n${i}-}"
	eval "ftitle=\${t${i}-}"

	case "${name}" in ?*)
		eval export '"FRAME${i}_NAME=${name}"'
		nameAttr=" name=\"${name}\""
	esac

	case "${ftitle}" in
		?*)
			eval export '"FRAME${i}_TITLE=${ftitle}"'
			titleAttr=" title=\"${ftitle}\""
			list="${list-}<li><a href=\"${uri}\">${ftitle}</a></li>"
			;;
		*) list="${list-}<li><a href=\"${uri}\">${uri}</a></li>";;
	esac

	frame="${frame-}<frame${nameAttr-}${titleAttr-} src=\"${uri}\" />"
done

ATTRIBUTES=$(eval "awk -- \"\${awkScript}\" ${attribute}")

export 'ATTRIBUTES' 'HEAD_CONTENT' 'TITLE' 'W3MPLUS_TEMPLATE_FRAMESET'

frameset="<frameset${ATTRIBUTES}>${frame-}<noframes><body><p>The frame cannot be displayed on your Web browser.</p><p>Please enable HTML Frame.</p><p>Frame page list</p><ul>${list-}</ul></body></noframes></frameset>"

case "${W3MPLUS_TEMPLATE_FRAMESET-}" in
	'') printf '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>%s</title>%s</head>%s</html>' "${TITLE}" "${HEAD_CONTENT}" "${frameset}";;
	*) org_lc sh -c "${W3MPLUS_FRAMESET_PROGRAM} \${@+\"\${@}\"}" 'sh' ${@+"${@}"};;
esac
