#!/usr/bin/env bash
# Generate the bot-link mTLS material for the TEST contour: a private CA, a gateway
# server leaf and a bot client leaf. The gateway requires the leaf + the bot the
# client leaf to bring up the reverse bot-link; the CA signs both so each peer trusts
# only the other.
#
# Production certificates come from PROD_ secrets, NOT this script. Private keys never
# leave the host/secrets; deploy/certs/ is gitignored. The script is idempotent: it
# reuses an existing CA + leaves unless --force is passed (rotation re-mints the
# leaves from the same long-lived CA).
#
# Usage:
#   deploy/gen-certs.sh [--force] [dir]
# Env:
#   BOTLINK_GATEWAY_NAME   gateway certificate SAN/CN (default: gateway, the compose
#                          service name the bot dials in the test contour)
set -euo pipefail

force=0
dir=""
for arg in "$@"; do
	case "$arg" in
	--force) force=1 ;;
	*) dir="$arg" ;;
	esac
done
dir="${dir:-$(cd "$(dirname "$0")" && pwd)/certs}"
gw_name="${BOTLINK_GATEWAY_NAME:-gateway}"

mkdir -p "$dir"
cd "$dir"

if [[ -f gateway.crt && -f bot.crt && "$force" -ne 1 ]]; then
	echo "gen-certs: certificates already present in $dir (use --force to rotate the leaves)"
	exit 0
fi

# CA: long-lived (10y), reused across leaf rotations.
if [[ ! -f ca.crt || ! -f ca.key ]]; then
	openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
		-keyout ca.key -out ca.crt -days 3650 -subj "/CN=scrabble-botlink-ca"
	echo "gen-certs: created CA"
fi

# Gateway server leaf (SAN matches the name the bot dials).
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
	-keyout gateway.key -out gateway.csr -subj "/CN=${gw_name}"
openssl x509 -req -in gateway.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
	-out gateway.crt -days 825 \
	-extfile <(printf "subjectAltName=DNS:%s,DNS:localhost\nextendedKeyUsage=serverAuth\nkeyUsage=critical,digitalSignature\n" "$gw_name")

# Bot client leaf.
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
	-keyout bot.key -out bot.csr -subj "/CN=scrabble-bot"
openssl x509 -req -in bot.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
	-out bot.crt -days 825 \
	-extfile <(printf "extendedKeyUsage=clientAuth\nkeyUsage=critical,digitalSignature\n")

rm -f gateway.csr bot.csr ca.srl
# The gateway and bot run on distroless **nonroot** (UID 65532) and bind-mount this
# dir read-only; a key owned by the deploy user must still be readable by that UID, so
# the leaves are world-readable (0644, like the .crt files). These are ephemeral
# TEST certificates regenerated every deploy on the trusted runner host; production
# keys come from PROD_ secrets, not this script. The CA key never enters a container —
# keep it owner-only.
chmod 644 ./ca.crt ./gateway.crt ./gateway.key ./bot.crt ./bot.key
chmod 600 ./ca.key
echo "gen-certs: wrote ca.crt, gateway.crt/key (CN=${gw_name}), bot.crt/key to $dir"
