#!/bin/bash
# Configure nginx for Dangerous Pi HTTP or HTTPS mode
# Switches nginx configuration based on HTTPS_ENABLED setting

set -e

# Configuration
ENV_FILE="/opt/dangerous-pi/.env"
NGINX_SITES_ENABLED="/etc/nginx/sites-enabled"
HTTP_CONFIG="/etc/nginx/sites-available/dangerous-pi.conf"
HTTPS_CONFIG="/opt/dangerous-pi/nginx/dangerous-pi-https.conf"
CERT_FILE="/opt/dangerous-pi/ssl/dangerous-pi.crt"
KEY_FILE="/opt/dangerous-pi/ssl/dangerous-pi.key"

# Source environment file to get HTTPS_ENABLED
HTTPS_ENABLED="false"
if [ -f "$ENV_FILE" ]; then
    # shellcheck source=/dev/null
    source "$ENV_FILE"
fi

echo "Configuring nginx for Dangerous Pi..."
echo "  HTTPS_ENABLED=$HTTPS_ENABLED"

if [ "$HTTPS_ENABLED" = "true" ]; then
    echo ""
    echo "HTTPS mode requested."

    # Check if certificate exists, generate if not
    if [ ! -f "$CERT_FILE" ] || [ ! -f "$KEY_FILE" ]; then
        echo "SSL certificate not found, generating..."
        /opt/dangerous-pi/scripts/generate-ssl-cert.sh
    fi

    # Verify certificate exists after generation attempt
    if [ ! -f "$CERT_FILE" ] || [ ! -f "$KEY_FILE" ]; then
        echo "ERROR: SSL certificate generation failed!"
        echo "Falling back to HTTP mode."
        HTTPS_ENABLED="false"
    else
        # Check if HTTPS config exists
        if [ ! -f "$HTTPS_CONFIG" ]; then
            echo "ERROR: HTTPS nginx config not found at $HTTPS_CONFIG"
            echo "Falling back to HTTP mode."
            HTTPS_ENABLED="false"
        fi
    fi
fi

# Remove existing symlink
rm -f "$NGINX_SITES_ENABLED/dangerous-pi.conf"

if [ "$HTTPS_ENABLED" = "true" ]; then
    # Use HTTPS config
    ln -sf "$HTTPS_CONFIG" "$NGINX_SITES_ENABLED/dangerous-pi.conf"
    echo ""
    echo "HTTPS mode enabled!"
    echo "  Config: $HTTPS_CONFIG"
    echo "  Certificate: $CERT_FILE"
    echo ""
    echo "Access the device at:"
    echo "  https://192.168.4.1/"
    echo "  https://dangerous-pi.local/"
    echo ""
    echo "Note: Browser will show certificate warning for self-signed cert."
else
    # Use HTTP-only config
    if [ -f "$HTTP_CONFIG" ]; then
        ln -sf "$HTTP_CONFIG" "$NGINX_SITES_ENABLED/dangerous-pi.conf"
        echo ""
        echo "HTTP-only mode enabled."
        echo "  Config: $HTTP_CONFIG"
        echo ""
        echo "Access the device at:"
        echo "  http://192.168.4.1/"
        echo "  http://dangerous-pi.local/"
    else
        echo "ERROR: HTTP nginx config not found at $HTTP_CONFIG"
        exit 1
    fi
fi

# Test nginx configuration
echo ""
echo "Testing nginx configuration..."
nginx -t

echo ""
echo "Nginx configuration complete."
echo "Run 'sudo systemctl reload nginx' to apply changes."
