#!/usr/bin/env bash
# Obtains the first Let's Encrypt certificate for ${DOMAIN} (+ optional
# ${FINANCE_DOMAIN}) via HTTP-01, then reloads the edge proxy so it switches
# to HTTPS automatically.
#
# Prereqs:
#   - DNS A/AAAA for ${DOMAIN} (and ${FINANCE_DOMAIN} if set) → this server
#   - ports 80 and 443 are open to the internet
#   - .env is filled (DOMAIN, LETSENCRYPT_EMAIL)
set -euo pipefail
cd "$(dirname "$0")/.."

# shellcheck disable=SC1091
set -a; . ./.env; set +a

: "${DOMAIN:?DOMAIN missing in .env}"
: "${LETSENCRYPT_EMAIL:?LETSENCRYPT_EMAIL missing in .env}"

CERT_DOMAINS=(-d "${DOMAIN}")
if [ -n "${FINANCE_DOMAIN:-}" ] && [ "${FINANCE_DOMAIN}" != "${DOMAIN}" ]; then
  CERT_DOMAINS+=(-d "${FINANCE_DOMAIN}")
fi

echo "==> Ensuring edge is up (HTTP) to serve the ACME challenge ..."
docker compose up -d edge

echo "==> Requesting certificate for ${CERT_DOMAINS[*]} ..."
docker compose run --rm --entrypoint certbot certbot \
  certonly --webroot -w /var/www/certbot \
  "${CERT_DOMAINS[@]}" \
  --email "${LETSENCRYPT_EMAIL}" \
  --agree-tos --no-eff-email --non-interactive

echo "==> Recreating edge so it picks up the certificate (HTTPS) ..."
docker compose up -d --force-recreate edge

echo "==> Done. https://${DOMAIN} should now be live."
if [ -n "${FINANCE_DOMAIN:-}" ]; then
  echo "         https://${FINANCE_DOMAIN} (finance portal)"
fi
