#!/bin/bash
# =========================================================
# SSL Certificate Manager (Env-Strict & Safe)
# =========================================================

CERT_DIR="certs"
SELF_KEY="$CERT_DIR/selfsigned.key"
SELF_CRT="$CERT_DIR/selfsigned.crt"
REAL_KEY="$CERT_DIR/real.key"
REAL_CRT="$CERT_DIR/real.crt"
SAN_CONFIG="$CERT_DIR/san.cnf"

mkdir -p "$CERT_DIR"

# Load environment variables strictly
if [ -f .env ]; then
    export $(grep -v '^#' .env | sed 's/#.*//' | grep -E '^[A-Z0-9_]+=.*' | xargs)
else
    echo "❌ .env file not found. Exiting."
    exit 1
fi

# Set safe defaults if any variables are missing
C="${C:-US}"
ST="${ST:-California}"
L="${L:-San Francisco}"
O="${O:-MyCompany}"
OU="${OU:-IT}"
CN="${CN:-localhost}"
EMAIL="${EMAIL:-admin@localhost}"
DNS="${DNS:-localhost}"
IP="${IP:-127.0.0.1}"
SSL_MODE="${SSL_MODE:-selfsigned}"

generate_self_signed() {
    echo "🔐 Generating self-signed certificate..."

    cat > "$SAN_CONFIG" <<EOF
[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req
prompt = no

[req_distinguished_name]
C = $C
ST = $ST
L = $L
O = $O
OU = $OU
CN = $CN
emailAddress = $EMAIL

[v3_req]
subjectAltName = @alt_names

[alt_names]
DNS.1 = $DNS
IP.1  = $IP
EOF

    openssl req -x509 -nodes -days 365 \
        -newkey rsa:2048 \
        -keyout "$SELF_KEY" \
        -out "$SELF_CRT" \
        -config "$SAN_CONFIG" \
        -extensions v3_req

    if [ $? -eq 0 ]; then
        echo "✅ Self-signed certificate created:"
        echo "  - $SELF_CRT"
        echo "  - $SELF_KEY"
    else
        echo "❌ Failed to create self-signed certificate."
        exit 1
    fi
}

generate_real_cert() {
    DOMAIN=${DOMAIN:-$DNS}  # Use DNS from .env if DOMAIN not explicitly set

    if [ -z "$DOMAIN" ]; then
        echo "❌ DOMAIN or DNS must be set in .env for real certificate."
        exit 1
    fi

    echo "📡 Using Certbot to generate certificate for $DOMAIN..."
    sudo certbot certonly --standalone -d "$DOMAIN"

    if [ $? -eq 0 ]; then
        echo "✅ Certificate generated successfully."
        sudo cp /etc/letsencrypt/live/$DOMAIN/fullchain.pem "$REAL_CRT"
        sudo cp /etc/letsencrypt/live/$DOMAIN/privkey.pem "$REAL_KEY"
        echo "🔐 Real certificate saved:"
        echo "  - $REAL_CRT"
        echo "  - $REAL_KEY"
    else
        echo "❌ Certbot failed. Please check your domain and try again."
        exit 1
    fi
}

show_menu() {
    echo ""
    echo "🧰 SSL Certificate Manager"
    echo "--------------------------"
    echo "1. Generate self-signed certificate"
    echo "2. Generate real certificate via Let’s Encrypt"
    echo "3. Use default from .env: SSL_MODE=$SSL_MODE"
    echo "4. Exit"
    echo ""
    echo -n "Choose an option [1-4]: "
    read OPTION

    case $OPTION in
        1) generate_self_signed ;;
        2) generate_real_cert ;;
        3)
            if [ "$SSL_MODE" = "real" ]; then
                generate_real_cert
            else
                generate_self_signed
            fi
            ;;
        4) echo "👋 Goodbye!" && exit 0 ;;
        *) echo "❌ Invalid option. Try again." && show_menu ;;
    esac
}

# Start the menu
show_menu
