#!/usr/bin/env bash
# Generates a self-signed CA and server certificate for Sysadmin Chronicles TLS.
# Idempotent — skips if certs already exist.
# Run this before building VMs. Called by install.sh automatically.
set -euo pipefail

SC_CERT_DIR="${SC_CERT_DIR:-$HOME/.local/share/sysadmin-chronicles/certs}"
mkdir -p "$SC_CERT_DIR"
chmod 700 "$SC_CERT_DIR"

if [[ -f "$SC_CERT_DIR/server.crt" && -f "$SC_CERT_DIR/server.key" && -f "$SC_CERT_DIR/ca.crt" ]]; then
  echo "TLS certs already exist at $SC_CERT_DIR — skipping."
  exit 0
fi

echo "Generating Axiom Works internal CA..."
openssl genrsa -out "$SC_CERT_DIR/ca.key" 4096 2>/dev/null
openssl req -new -x509 -days 3650 \
  -key "$SC_CERT_DIR/ca.key" \
  -out "$SC_CERT_DIR/ca.crt" \
  -subj "/CN=Axiom Works Internal CA/O=Axiom Works" 2>/dev/null

echo "Generating server certificate..."
openssl genrsa -out "$SC_CERT_DIR/server.key" 4096 2>/dev/null
openssl req -new \
  -key "$SC_CERT_DIR/server.key" \
  -out "$SC_CERT_DIR/server.csr" \
  -subj "/CN=portal.axiomworks.internal/O=Axiom Works" 2>/dev/null

cat > "$SC_CERT_DIR/server.ext" <<'EXTEOF'
subjectAltName=DNS:portal.axiomworks.internal,DNS:sage.axiomworks.internal,DNS:axiomworks.corp,DNS:www.axiomworks.corp,DNS:*.axiomworks.internal,DNS:*.axiomworks.corp
EXTEOF

openssl x509 -req -days 3650 \
  -in "$SC_CERT_DIR/server.csr" \
  -CA "$SC_CERT_DIR/ca.crt" \
  -CAkey "$SC_CERT_DIR/ca.key" \
  -CAcreateserial \
  -out "$SC_CERT_DIR/server.crt" \
  -extfile "$SC_CERT_DIR/server.ext" 2>/dev/null

chmod 600 "$SC_CERT_DIR/ca.key" "$SC_CERT_DIR/server.key"
rm -f "$SC_CERT_DIR/server.csr" "$SC_CERT_DIR/server.ext"

echo "TLS certs generated at $SC_CERT_DIR"
echo "  CA cert:     $SC_CERT_DIR/ca.crt"
echo "  Server cert: $SC_CERT_DIR/server.crt"
echo "  Server key:  $SC_CERT_DIR/server.key"
