#!/bin/bash

# SSL Certificate Generation Script for Portfolio Tracker
# This script generates self-signed certificates for development and provides guidance for production

set -e

CERT_DIR="./certs"
DOMAIN="${SSL_DOMAIN:-localhost}"
COUNTRY="${SSL_COUNTRY:-US}"
STATE="${SSL_STATE:-CA}"
CITY="${SSL_CITY:-San Francisco}"
ORG="${SSL_ORG:-Portfolio Tracker}"
ORG_UNIT="${SSL_ORG_UNIT:-Development}"
EMAIL="${SSL_EMAIL:-admin@portfoliotracker.local}"

echo "🔐 Generating SSL certificates for Portfolio Tracker"
echo "Domain: $DOMAIN"
echo "Organization: $ORG"

# Create certificates directory
mkdir -p "$CERT_DIR"

# Generate private key
echo "📝 Generating private key..."
openssl genrsa -out "$CERT_DIR/key.pem" 2048

# Generate certificate signing request
echo "📝 Generating certificate signing request..."
openssl req -new -key "$CERT_DIR/key.pem" -out "$CERT_DIR/csr.pem" -subj "/C=$COUNTRY/ST=$STATE/L=$CITY/O=$ORG/OU=$ORG_UNIT/CN=$DOMAIN/emailAddress=$EMAIL"

# Generate self-signed certificate
echo "📝 Generating self-signed certificate..."
openssl x509 -req -days 365 -in "$CERT_DIR/csr.pem" -signkey "$CERT_DIR/key.pem" -out "$CERT_DIR/cert.pem" -extensions v3_req -extfile <(
cat <<EOF
[v3_req]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = $DOMAIN
DNS.2 = *.$DOMAIN
DNS.3 = localhost
DNS.4 = *.localhost
IP.1 = 127.0.0.1
IP.2 = ::1
EOF
)

# Generate DH parameters for enhanced security
echo "📝 Generating DH parameters (this may take a while)..."
openssl dhparam -out "$CERT_DIR/dhparam.pem" 2048

# Set appropriate permissions
chmod 600 "$CERT_DIR/key.pem"
chmod 644 "$CERT_DIR/cert.pem"
chmod 644 "$CERT_DIR/dhparam.pem"

# Clean up CSR file
rm "$CERT_DIR/csr.pem"

echo "✅ SSL certificates generated successfully!"
echo ""
echo "Files created:"
echo "  - $CERT_DIR/key.pem (private key)"
echo "  - $CERT_DIR/cert.pem (certificate)"
echo "  - $CERT_DIR/dhparam.pem (DH parameters)"
echo ""
echo "To use HTTPS in development:"
echo "  export HTTPS_ENABLED=true"
echo "  export HTTPS_KEY_PATH=$CERT_DIR/key.pem"
echo "  export HTTPS_CERT_PATH=$CERT_DIR/cert.pem"
echo ""
echo "⚠️  For production, use certificates from a trusted CA like Let's Encrypt:"
echo "  1. Install certbot: https://certbot.eff.org/"
echo "  2. Generate certificate: certbot certonly --standalone -d yourdomain.com"
echo "  3. Update paths to point to Let's Encrypt certificates"
echo ""
echo "🔒 Security recommendations:"
echo "  - Keep private keys secure and never commit them to version control"
echo "  - Use strong cipher suites (already configured in secure-server.ts)"
echo "  - Enable HSTS headers (already configured)"
echo "  - Consider using OCSP stapling for production"
echo "  - Regularly rotate certificates (Let's Encrypt auto-renews every 90 days)"