#!/bin/sh
# httpd-utils
# Written in 2020 by Lucas
# CC0 1.0 Universal/Public domain - No rights reserved
#
# To the extent possible under law, the author(s) have dedicated all
# copyright and related and neighboring rights to this software to the
# public domain worldwide. This software is distributed without any
# warranty. You should have received a copy of the CC0 Public Domain
# Dedication along with this software. If not, see
# <http://creativecommons.org/publicdomain/zero/1.0/>.

usage()
{
	printf "Usage: %s domain domain_v4 domain_v6\n" "${0##*/}" >&2
	exit 1
}

list_codes()
{
	case $1 in
	1xx)	q='1[0-9][0-9]' ;;
	2xx)	q='2[0-9][0-9]' ;;
	3xx)	q='3[0-9][0-9]' ;;
	4xx)	q='4[0-9][0-9]' ;;
	5xx)	q='5[0-9][0-9]' ;;
	*)	q=X ;;
	esac
	grep -x -- "$q" codes.txt
}

show_category()
{
	_t=$1 _cc=$2
	cat - <<EOF
		<dl>
			<dt>$_t $_cc</dt>
EOF

	for _c in $(list_codes "$_cc"); do
		printf '\t\t\t<dd><a href="/c/%u">%u</a></dd>\n' "$_c" "$_c"
	done
	printf "\t\t</dl>\n"
}

[ $# -eq 3 ] || usage
domain=$1 domain_v4=$2 domain_v6=$3

cat - <<EOF
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>$domain</title>
		<style>
* {
	margin: 0;
	padding: 0;
}

body {
	width: 800px;
	margin: 20px auto;
	font-size: 16px;
	line-height: 20px;
}

h1,
h2,
dl {
	margin-bottom: 20px;
}

dd {
	margin-left: 20px;
}

h1 {
	font-size: 32px;
	line-height: 40px;
}

h2 {
	font-size: 24px;
	line-height: 40px;
}
		</style>
	</head>
	<body>
		<h1>$domain</h1>

		<h2>Utilities</h2>
		<dl>
			<dt><a href="/ip">/ip</a></dt>
			<dd>shows client IP.</dd>
			<dt><a href="//$domain_v4/ip">$domain_v4/ip</a></dt>
			<dd>shows client IP, only listens on a IPv4 address.</dd>
			<dt><a href="//$domain_v6/ip">$domain_v6/ip</a></dt>
			<dd>shows client IP, only listens on a IPv6 address.</dd>
		</dl>

		<h2>HTTP status codes</h2>
EOF

show_category "Informational" 1xx
show_category "Successful" 2xx
show_category "Redirection" 3xx
show_category "Client Error" 4xx
show_category "Server Error" 5xx

cat - <<EOF
	</body>
</html>
EOF
