#!/usr/bin/env bash
# Generate a self-signed certificate for local development.
# The cert is shared by both ng serve (--ssl-cert/--ssl-key) and the Express API.

set -e

DIR="$(cd "$(dirname "$0")" && pwd)"
CERT_DIR="$DIR/.certs"

if [ -f "$CERT_DIR/localhost.crt" ] && [ -f "$CERT_DIR/localhost.key" ]; then
  echo "Certs already exist at $CERT_DIR – skipping generation."
  echo "  Delete .certs/ and re-run to regenerate."
  exit 0
fi

mkdir -p "$CERT_DIR"

# Optional: include a LAN/public IP in the certificate SAN (required when clients connect by IP).
# Example: SERVER_IP=46.59.68.77 ./generate-cert.sh
SAN="DNS:localhost,IP:127.0.0.1,IP:0.0.0.0"
if [ -n "${SERVER_IP:-}" ]; then
  SAN="$SAN,IP:$SERVER_IP"
  echo "Including SERVER_IP=$SERVER_IP in certificate SAN."
fi

echo "Generating self-signed certificate..."
openssl req -x509 -nodes -days 3650 \
  -newkey rsa:2048 \
  -keyout "$CERT_DIR/localhost.key" \
  -out "$CERT_DIR/localhost.crt" \
  -subj "/CN=localhost" \
  -addext "subjectAltName=$SAN"

echo "Done. Certificate written to:"
echo "  $CERT_DIR/localhost.crt"
echo "  $CERT_DIR/localhost.key"
