#!/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 ipv4 domain_v6 ipv6\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
}

print_block_return()
{
	_c=$1 _l=${2:-}

	_fmt='\tlocation "/c/%u" { block return %u'${_l:+' "%s"'}' }\n'
	printf "$_fmt" $_c $_c $_l
}

[ $# -eq 5 ] || usage
domain=$1 domain_v4=$2 ipv4=$3 domain_v6=$4 ipv6=$5

cat - <<EOF
server "$domain" {
	listen on $ipv4 port http
	listen on $ipv6 port http
	listen on $ipv4 tls port https
	listen on $ipv6 tls port https
	no log

	alias "$domain_v4"
	alias "$domain_v6"

	tls {
		certificate "/etc/ssl/$domain.fullchain.pem"
		key "/etc/ssl/private/$domain.key"
	}

	location "/.well-known/acme-challenge/*" {
		root "/acme"
		request strip 2
	}

	root "/htdocs/$domain"
	location "/ip" { fastcgi }
EOF

for _c in $(list_codes 1xx); do
	print_block_return "$_c"
done
for _c in $(list_codes 2xx); do
	print_block_return "$_c"
done
for _c in $(list_codes 3xx); do
	print_block_return "$_c" "/"
done
for _c in $(list_codes 4xx); do
	print_block_return "$_c"
done
for _c in $(list_codes 5xx); do
	print_block_return "$_c"
done

printf "}\n"
