#!/usr/bin/env bash
# Generate a self-signed TLS cert for local/dev HTTPS (no domain or purchase needed).
# Use this so you can test camera + geolocation from your phone (they require HTTPS).
#
# Usage:
#   ./scripts/gen-dev-cert.sh              # cert for localhost + 127.0.0.1 only
#   ./scripts/gen-dev-cert.sh 192.168.2.214 # cert for that LAN IP so phone can use https://192.168.2.214:3000
#
# Then run: npm run dev
# On your phone: open https://YOUR_IP:3000 (accept the browser warning once).

set -e
DIR="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$DIR/.dev-certs"
mkdir -p "$OUT"
KEY="$OUT/key.pem"
CERT="$OUT/cert.pem"

IP="${1:-127.0.0.1}"
# SAN: always localhost + 127.0.0.1; add the given IP if it's not localhost
if [ "$IP" = "127.0.0.1" ] || [ "$IP" = "localhost" ]; then
  SAN="subjectAltName=IP:127.0.0.1,DNS:localhost"
else
  SAN="subjectAltName=IP:127.0.0.1,IP:${IP},DNS:localhost"
fi

openssl req -x509 -newkey rsa:2048 -keyout "$KEY" -out "$CERT" -days 365 -nodes \
  -subj "/CN=localhost" \
  -addext "$SAN"

echo "Created $KEY and $CERT"
echo ""
echo "Next: run  npm run dev"
if [ "$IP" != "127.0.0.1" ] && [ "$IP" != "localhost" ]; then
  echo "On your phone: open  https://${IP}:3000  (accept the security warning once)"
fi
