#!/usr/bin/env bash
#
# generate-certs.sh — mint the unibus bus's self-signed CA and the NATS server
# certificate. Run once on a trusted machine; distribute ca.crt to clients and
# server.crt/server.key to the bus host (server.key by a secure channel, never
# git). Re-running regenerates the server cert; pass --force to also regenerate
# the CA (which invalidates every client that pinned the old ca.crt).
#
# SANs cover the public IP, the WireGuard IP, the om hostname, plus localhost so
# the operator can smoke-test the TLS handshake on the box. Override via env:
#   UNIBUS_PUBLIC_IP (default 135.125.201.30)
#   UNIBUS_WG_IP     (default 10.42.0.1)
#   UNIBUS_HOSTNAME  (default om)
#
# Key material: EC P-256 (widely supported by Go's crypto/tls and nats-server).
set -euo pipefail

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$DIR"

PUBLIC_IP="${UNIBUS_PUBLIC_IP:-135.125.201.30}"
WG_IP="${UNIBUS_WG_IP:-10.42.0.1}"
HOSTNAME_OM="${UNIBUS_HOSTNAME:-om}"
DAYS_CA=3650
DAYS_SRV=825

force=0
[[ "${1:-}" == "--force" ]] && force=1

# --- CA (long-lived; only the cert is public) ---
if [[ ! -f ca.crt || ! -f ca.key || $force -eq 1 ]]; then
  echo "==> generating CA"
  openssl ecparam -name prime256v1 -genkey -noout -out ca.key
  chmod 600 ca.key
  openssl req -x509 -new -key ca.key -sha256 -days "$DAYS_CA" \
    -subj "/CN=unibus-ca" -out ca.crt
else
  echo "==> reusing existing CA (pass --force to regenerate)"
fi

# --- server certificate, signed by the CA, with the bus SANs ---
echo "==> generating server certificate (SAN: $PUBLIC_IP, $WG_IP, $HOSTNAME_OM, localhost, 127.0.0.1)"
openssl ecparam -name prime256v1 -genkey -noout -out server.key
chmod 600 server.key
openssl req -new -key server.key -subj "/CN=unibus-bus" -out server.csr

cat > server.ext <<EOF
subjectAltName=IP:${PUBLIC_IP},IP:${WG_IP},DNS:${HOSTNAME_OM},DNS:localhost,IP:127.0.0.1
extendedKeyUsage=serverAuth
keyUsage=digitalSignature,keyEncipherment
EOF

openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
  -sha256 -days "$DAYS_SRV" -extfile server.ext -out server.crt

rm -f server.csr server.ext ca.srl

echo "==> done:"
echo "    ca.crt      -> embed/distribute to every client (public)"
echo "    server.crt  -> deploy to the bus host"
echo "    server.key  -> deploy to the bus host over a secure channel (NEVER git)"
echo
echo "verify SANs with:"
echo "    openssl x509 -in server.crt -noout -text | grep -A1 'Subject Alternative Name'"
