#!/bin/bash
#
# Generate self-signed SSL certificate for local HTTPS
#
# This creates a certificate valid for 365 days. While browsers will show
# a warning (since it's self-signed), the connection will still be encrypted.
#

set -e

CERT_DIR="ssl"
CERT_FILE="$CERT_DIR/cert.pem"
KEY_FILE="$CERT_DIR/key.pem"

echo "=== Camera Server SSL Certificate Generator ==="
echo

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

# Generate self-signed certificate
echo "Generating self-signed certificate..."
openssl req -x509 -newkey rsa:4096 \
    -keyout "$KEY_FILE" \
    -out "$CERT_FILE" \
    -days 365 \
    -nodes \
    -subj "/C=US/ST=State/L=City/O=CameraServer/CN=camera.local"

# Set proper permissions
chmod 600 "$KEY_FILE"
chmod 644 "$CERT_FILE"

echo
echo "✓ Certificate generated successfully!"
echo
echo "Files created:"
echo "  - Certificate: $CERT_FILE"
echo "  - Private key: $KEY_FILE"
echo
echo "Note: Browsers will show a security warning because this is self-signed."
echo "This is normal for local development. The connection is still encrypted."
echo
echo "To trust this certificate:"
echo "  - On macOS: Open Keychain Access, import cert.pem, mark as trusted"
echo "  - On Linux: Copy to /usr/local/share/ca-certificates/ and run update-ca-certificates"
echo "  - On Windows: Import cert.pem into Trusted Root Certification Authorities"
echo
