#!/bin/sh
# Generate self-signed TLS certificates in DER format for the 3-node cluster test.
# Usage: ./gen-certs.sh

set -e

OUTDIR="$(dirname "$0")/certs"
mkdir -p "$OUTDIR"

echo "Generating CA key and certificate..."
openssl req -x509 -newkey rsa:2048 -nodes \
    -keyout "$OUTDIR/ca-key.pem" \
    -out "$OUTDIR/ca-cert.pem" \
    -days 365 -subj "/CN=authdb-cluster-ca"

for NODE in node1 node2 node3; do
    echo "Generating certificate for $NODE..."

    # Create SAN config
    cat > "$OUTDIR/$NODE.cnf" <<EOF
[req]
distinguished_name = req_dn
req_extensions = v3_req
prompt = no

[req_dn]
CN = $NODE

[v3_req]
subjectAltName = DNS:$NODE,DNS:localhost,IP:127.0.0.1
EOF

    # Generate key + CSR
    openssl req -newkey rsa:2048 -nodes \
        -keyout "$OUTDIR/$NODE-key.pem" \
        -out "$OUTDIR/$NODE.csr" \
        -config "$OUTDIR/$NODE.cnf"

    # Sign with CA
    openssl x509 -req -in "$OUTDIR/$NODE.csr" \
        -CA "$OUTDIR/ca-cert.pem" -CAkey "$OUTDIR/ca-key.pem" \
        -CAcreateserial \
        -out "$OUTDIR/$NODE-cert.pem" \
        -days 365 \
        -extensions v3_req -extfile "$OUTDIR/$NODE.cnf"

    # Convert to DER (authdb expects DER format)
    openssl x509 -in "$OUTDIR/$NODE-cert.pem" -outform DER -out "$OUTDIR/$NODE-cert.der"
    openssl rsa  -in "$OUTDIR/$NODE-key.pem"  -outform DER -out "$OUTDIR/$NODE-key.der"

    # Cleanup intermediates
    rm -f "$OUTDIR/$NODE.csr" "$OUTDIR/$NODE.cnf"
done

rm -f "$OUTDIR/ca-cert.srl"

echo "Certificates generated in $OUTDIR/"
ls -la "$OUTDIR/"
