#!/bin/bash
# Generate self-signed SSL certificate for Dangerous Pi
# Supports first-boot auto-generation or manual regeneration

set -e

# Configuration
CERT_DIR="/opt/dangerous-pi/ssl"
CERT_FILE="$CERT_DIR/dangerous-pi.crt"
KEY_FILE="$CERT_DIR/dangerous-pi.key"
DAYS_VALID=3650  # 10 years

# Certificate subject
SUBJECT="/CN=Dangerous Pi/O=Dangerous Pi/C=US"

# Subject Alternative Names (SANs)
# - The AP gateway IP
# - mDNS hostname
# - Bare hostname
# - Localhost for development
SANS="IP:192.168.4.1,DNS:dangerous-pi.local,DNS:dangerous-pi,DNS:localhost,IP:127.0.0.1"

usage() {
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Generate self-signed SSL certificate for Dangerous Pi HTTPS."
    echo ""
    echo "Options:"
    echo "  --force     Regenerate certificate even if one exists"
    echo "  --cert-dir  Specify certificate directory (default: $CERT_DIR)"
    echo "  --help      Show this help message"
    echo ""
    echo "The certificate will be valid for:"
    echo "  - 192.168.4.1 (AP gateway IP)"
    echo "  - dangerous-pi.local (mDNS hostname)"
    echo "  - dangerous-pi (bare hostname)"
    echo "  - localhost"
}

FORCE=false

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --force)
            FORCE=true
            shift
            ;;
        --cert-dir)
            CERT_DIR="$2"
            CERT_FILE="$CERT_DIR/dangerous-pi.crt"
            KEY_FILE="$CERT_DIR/dangerous-pi.key"
            shift 2
            ;;
        --help)
            usage
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            usage
            exit 1
            ;;
    esac
done

# Create SSL directory if it doesn't exist
mkdir -p "$CERT_DIR"

# Check if certificate already exists
if [ -f "$CERT_FILE" ] && [ "$FORCE" = false ]; then
    echo "Certificate already exists at $CERT_FILE"
    echo "Use --force to regenerate."
    exit 0
fi

echo "Generating self-signed SSL certificate for Dangerous Pi..."
echo "  Certificate: $CERT_FILE"
echo "  Private key: $KEY_FILE"
echo "  Validity: $DAYS_VALID days"
echo ""

# Generate private key and certificate with SANs
# Using EC P-256 for better performance on Raspberry Pi
openssl req -x509 -nodes -days "$DAYS_VALID" \
    -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \
    -keyout "$KEY_FILE" \
    -out "$CERT_FILE" \
    -subj "$SUBJECT" \
    -addext "subjectAltName=$SANS" \
    -addext "basicConstraints=CA:FALSE" \
    -addext "keyUsage=digitalSignature,keyEncipherment" \
    -addext "extendedKeyUsage=serverAuth"

# Set secure permissions
# Private key: owner read/write only
chmod 600 "$KEY_FILE"
# Certificate: world readable
chmod 644 "$CERT_FILE"

# Set ownership to root
if [ "$EUID" -eq 0 ]; then
    chown root:root "$KEY_FILE" "$CERT_FILE"
fi

echo ""
echo "SSL certificate generated successfully!"
echo ""
echo "Certificate details:"
openssl x509 -in "$CERT_FILE" -noout -subject -dates -ext subjectAltName 2>/dev/null || \
    openssl x509 -in "$CERT_FILE" -noout -subject -dates
echo ""
echo "To enable HTTPS, set HTTPS_ENABLED=true in /opt/dangerous-pi/.env"
echo "Then restart the services: sudo systemctl restart dangerous-pi-nginx-config nginx"
