#!/bin/bash
# Generate Development TLS Certificates for Foxhunt HFT Services
# Wave 75 Agent 6 - Quick Fix for Missing Certificates

set -e

CERT_DIR="/etc/foxhunt/certs"
BACKUP_DIR="./certs_dev"

echo "========================================="
echo " Foxhunt HFT - TLS Certificate Generator"
echo "========================================="
echo ""

# Check if running as root (required for /etc/foxhunt)
if [ "$EUID" -ne 0 ]; then
    echo "ERROR: This script must be run as root (for /etc/foxhunt access)"
    echo ""
    echo "Usage: sudo ./generate_dev_certs.sh"
    echo ""
    echo "Alternative: Generate in local directory without sudo"
    read -p "Generate certificates in ./certs_dev instead? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        CERT_DIR="./certs_dev"
        echo "Using local directory: $CERT_DIR"
    else
        exit 1
    fi
fi

# Create certificate directory
echo "[1/5] Creating certificate directory: $CERT_DIR"
mkdir -p "$CERT_DIR"
cd "$CERT_DIR"

# Generate CA private key
echo "[2/5] Generating CA private key..."
openssl genrsa -out ca.key 4096 2>/dev/null

# Generate CA certificate
echo "[3/5] Generating CA certificate..."
openssl req -new -x509 -days 3650 -key ca.key -out ca.crt \
    -subj "/C=US/ST=California/L=San Francisco/O=Foxhunt HFT/OU=Development/CN=Foxhunt Root CA" \
    2>/dev/null

# Generate server private key
echo "[4/5] Generating server private key..."
openssl genrsa -out server.key 4096 2>/dev/null

# Create server certificate signing request
echo "[5/5] Generating server certificate..."
openssl req -new -key server.key -out server.csr \
    -subj "/C=US/ST=California/L=San Francisco/O=Foxhunt HFT/OU=Services/CN=localhost" \
    2>/dev/null

# Create SAN configuration for localhost + service names
cat > san.cnf <<EOF
[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req

[req_distinguished_name]

[v3_req]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
DNS.2 = trading.foxhunt.local
DNS.3 = backtesting.foxhunt.local
DNS.4 = ml-training.foxhunt.local
DNS.5 = api.foxhunt.local
IP.1 = 127.0.0.1
IP.2 = 0.0.0.0
EOF

# Sign server certificate with CA
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
    -out server.crt -days 365 -extensions v3_req -extfile san.cnf 2>/dev/null

# Generate client certificates (for mutual TLS)
echo "[BONUS] Generating client certificates..."
openssl genrsa -out client.key 4096 2>/dev/null
openssl req -new -key client.key -out client.csr \
    -subj "/C=US/ST=California/L=San Francisco/O=Foxhunt HFT/OU=Clients/CN=foxhunt-client" \
    2>/dev/null
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
    -out client.crt -days 365 2>/dev/null

# Set proper permissions
chmod 600 *.key
chmod 644 *.crt

# Clean up temporary files
rm -f *.csr *.srl san.cnf

echo ""
echo "========================================="
echo " Certificates Generated Successfully!"
echo "========================================="
echo ""
echo "Location: $CERT_DIR"
echo ""
echo "Files created:"
ls -lh "$CERT_DIR"
echo ""
echo "Certificate Details:"
echo "-------------------"
openssl x509 -in server.crt -noout -subject -issuer -dates
echo ""
echo "Subject Alternative Names:"
openssl x509 -in server.crt -noout -text | grep -A 1 "Subject Alternative Name"
echo ""

if [ "$CERT_DIR" != "/etc/foxhunt/certs" ]; then
    echo "⚠️  IMPORTANT: Certificates generated in local directory!"
    echo ""
    echo "To use these certificates, copy them to /etc/foxhunt/certs:"
    echo ""
    echo "  sudo mkdir -p /etc/foxhunt/certs"
    echo "  sudo cp $CERT_DIR/* /etc/foxhunt/certs/"
    echo "  sudo chmod 600 /etc/foxhunt/certs/*.key"
    echo "  sudo chmod 644 /etc/foxhunt/certs/*.crt"
    echo ""
fi

echo "Next steps:"
echo "1. Verify certificates: openssl verify -CAfile $CERT_DIR/ca.crt $CERT_DIR/server.crt"
echo "2. Restart services: sudo systemctl restart foxhunt-*"
echo "3. Run health check: ./quick_health_check.sh"
echo ""
echo "⚠️  NOTE: These are DEVELOPMENT certificates (self-signed)"
echo "   For production, use proper CA-signed certificates or Vault PKI"
echo ""
