#!/bin/bash

readonly DOMAINS=(
	"hello.example.org"
)

# Process script arguments.
DUMMY=false
while (( $# > 0 )); do case $1 in
	--dummy)
		DUMMY=true
		shift;;
	*)
		echo "Invalid argument" >&2
		exit 1
esac done

populate_pem_file() {
	cat "$1" "$2" > /root/certs.pem
	chmod 644 /root/certs.pem
}

# Create self-signed dummy certificates.
if "${DUMMY}"; then
	# Create disposable key files at a temporary location.
	TMP="$(mktemp --directory)"
	PWD="$(openssl rand -base64 32)"
	openssl genrsa -out "${TMP}/t.key" -passout "pass:${PWD}" 4096
	openssl req -new -key "${TMP}/t.key" -out "${TMP}/t.csr" \
		-subj "/C=/ST=/L=/O=/OU=/CN=/emailAddress=" \
		-passin "pass:${PWD}"
	openssl x509 -req -days 1 -in "${TMP}/t.csr" -signkey "${TMP}/t.key" -out "${TMP}/t.crt"
	# Generate `/root/certs.pem` file and clean up.
	populate_pem_file "${TMP}/t.key" "${TMP}/t.crt"
	rm -rf "${TMP}"
	exit 0
fi

# Issue certificates for all domains via Let’s Encrypt.
domain_flags=()
for d in "${DOMAINS[@]}"; do domain_flags+=(--domain "${d}"); done
acme.sh --issue --stateless \
	--keylength 4096 \
	"${domain_flags[@]}" \
	--server letsencrypt

populate_pem_file \
	"/root/.acme.sh/${DOMAINS[0]}/fullchain.cer" \
	"/root/.acme.sh/${DOMAINS[0]}/${DOMAINS[0]}.key"

# Restart gateway service to apply certificates.
docker compose \
	--file /root/src/docker-compose.yml \
	restart gateway
