#!/bin/sh
set -e

# Defaults
: "${CERT_PASSWORD:=changeit}"
: "${CN_SERVER:=localhost}"
: "${CN_CLIENT:=esp32-device}"

echo "==> Generating development CA, server, and client certificates (for mTLS)"
echo "    Password for server.pfx: ${CERT_PASSWORD}"

# Clean previous
rm -f ca.key ca.crt server.key server.csr server.crt server.pfx client.key client.csr client.crt client.pfx \
      client.pem client.key.pem server.pem server.key.pem server-chain.crt

# 1) CA (self-signed)
openssl genrsa -out ca.key 4096
openssl req -x509 -new -nodes -key ca.key -sha256 -days 3650 -subj "/CN=Dev CA" -out ca.crt

# 2) Server key + CSR with SANs (localhost + 127.0.0.1)
cat > server.cnf <<EOF
[req]
default_bits       = 2048
prompt             = no
default_md         = sha256
req_extensions     = req_ext
distinguished_name = dn

[dn]
CN = ${CN_SERVER}

[req_ext]
subjectAltName = @alt_names

[alt_names]
DNS.1   = localhost
IP.1    = 127.0.0.1
EOF

openssl genrsa -out server.key 2048
openssl req -new -key server.key -out server.csr -config server.cnf

# 2b) Sign server CSR with CA
cat > ca.cnf <<EOF
[ca]
default_ca = CA_default
[CA_default]
copy_extensions = copy
EOF

openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 825 -sha256 -extfile server.cnf -extensions req_ext

# Export server cert+key to PKCS#12 for Kestrel
openssl pkcs12 -export -out server.pfx -inkey server.key -in server.crt -certfile ca.crt -passout pass:${CERT_PASSWORD}

# PEM variants (optional)
cp server.crt server.pem
cp server.key server.key.pem
cat server.crt ca.crt > server-chain.crt

# 3) Client key/cert for device testing
openssl genrsa -out client.key 2048
openssl req -new -key client.key -out client.csr -subj "/CN=${CN_CLIENT}"
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 825 -sha256

# PKCS#12 for client (optional)
openssl pkcs12 -export -out client.pfx -inkey client.key -in client.crt -certfile ca.crt -passout pass:${CERT_PASSWORD}

# Convenience PEM for ESP32 (paste into firmware or convert as needed)
cp client.crt client.pem

echo "==> Done."
echo "Artifacts created:"
echo "  - ca.crt (CA certificate to trust on ESP32)"
echo "  - server.pfx (for Kestrel, protected by CERT_PASSWORD)"
echo "  - server.crt/server.key (PEM)"
echo "  - client.crt/client.key (PEM) and client.pfx (optional)"
