#!/usr/bin/env bash

# ============================================================================
# Nginx Configuration Generator
# Interactive script to generate production-ready Nginx configurations
# ============================================================================

set -euo pipefail

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEMPLATES_DIR="$(dirname "$SCRIPT_DIR")/templates"

# ============================================================================
# Helper Functions
# ============================================================================

print_header() {
    echo ""
    echo -e "${BLUE}============================================================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}============================================================================${NC}"
    echo ""
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ $1${NC}"
}

# ============================================================================
# Main Script
# ============================================================================

print_header "Nginx Configuration Generator"

echo "This script will guide you through creating a production-ready Nginx configuration."
echo ""

# ============================================================================
# Step 1: Select Configuration Type
# ============================================================================

print_info "Step 1: Select Configuration Type"
echo ""
echo "Available configuration types:"
echo "  1) Reverse Proxy       - Proxy requests to a backend application"
echo "  2) Load Balancer       - Distribute traffic across multiple backends"
echo "  3) Static Site         - Serve static files (HTML, CSS, JS)"
echo "  4) SSL Termination     - SSL/TLS termination for legacy apps"
echo "  5) API Gateway         - Complete API gateway with CORS and rate limiting"
echo ""

read -p "Select configuration type [1-5]: " config_type

case $config_type in
    1)
        CONFIG_NAME="reverse-proxy"
        CONFIG_DESC="Reverse Proxy"
        TEMPLATE_FILE="$TEMPLATES_DIR/reverse-proxy/reverse-proxy.conf"
        ;;
    2)
        CONFIG_NAME="load-balancer"
        CONFIG_DESC="Load Balancer"
        TEMPLATE_FILE="$TEMPLATES_DIR/load-balancer/load-balancer.conf"
        ;;
    3)
        CONFIG_NAME="static-site"
        CONFIG_DESC="Static Site"
        TEMPLATE_FILE="$TEMPLATES_DIR/static-site/static-site.conf"
        ;;
    4)
        CONFIG_NAME="ssl-termination"
        CONFIG_DESC="SSL Termination"
        TEMPLATE_FILE="$TEMPLATES_DIR/ssl-termination/ssl-termination.conf"
        ;;
    5)
        CONFIG_NAME="api-gateway"
        CONFIG_DESC="API Gateway"
        TEMPLATE_FILE="$TEMPLATES_DIR/api-gateway/api-gateway.conf"
        ;;
    *)
        print_error "Invalid selection"
        exit 1
        ;;
esac

print_success "Selected: $CONFIG_DESC"

# Check if template exists
if [[ ! -f "$TEMPLATE_FILE" ]]; then
    print_error "Template file not found: $TEMPLATE_FILE"
    exit 1
fi

# ============================================================================
# Step 2: Gather Configuration Details
# ============================================================================

echo ""
print_info "Step 2: Configuration Details"
echo ""

# Domain name
read -p "Enter domain name (e.g., example.com): " domain_name
if [[ -z "$domain_name" ]]; then
    print_error "Domain name is required"
    exit 1
fi

# Include www subdomain?
read -p "Include www.$domain_name? [Y/n]: " include_www
include_www=${include_www:-Y}

if [[ "$include_www" =~ ^[Yy]$ ]]; then
    server_name="$domain_name www.$domain_name"
else
    server_name="$domain_name"
fi

# SSL certificate paths
echo ""
print_info "SSL Certificate Configuration"
read -p "SSL certificate path [/etc/ssl/certs/$domain_name.crt]: " ssl_cert
ssl_cert=${ssl_cert:-"/etc/ssl/certs/$domain_name.crt"}

read -p "SSL certificate key path [/etc/ssl/private/$domain_name.key]: " ssl_key
ssl_key=${ssl_key:-"/etc/ssl/private/$domain_name.key"}

# Backend configuration (not needed for static site)
if [[ "$CONFIG_NAME" != "static-site" ]]; then
    echo ""
    print_info "Backend Configuration"

    if [[ "$CONFIG_NAME" == "load-balancer" ]]; then
        read -p "Number of backend servers [3]: " backend_count
        backend_count=${backend_count:-3}

        declare -a backends
        for ((i=1; i<=backend_count; i++)); do
            read -p "Backend $i address (host:port) [backend$i.example.com:8080]: " backend
            backend=${backend:-"backend$i.example.com:8080"}
            backends+=("$backend")
        done
    else
        read -p "Backend URL (e.g., localhost:3000 or http://backend:8080): " backend_url
        backend_url=${backend_url:-"localhost:3000"}

        # Strip http:// or https:// if present
        backend_url=${backend_url#http://}
        backend_url=${backend_url#https://}
    fi
fi

# Static site root directory
if [[ "$CONFIG_NAME" == "static-site" ]]; then
    echo ""
    read -p "Root directory for static files [/var/www/html]: " root_dir
    root_dir=${root_dir:-"/var/www/html"}
fi

# Output filename
echo ""
read -p "Output filename [$domain_name.conf]: " output_file
output_file=${output_file:-"$domain_name.conf"}

# ============================================================================
# Step 3: Generate Configuration
# ============================================================================

echo ""
print_info "Step 3: Generating Configuration"

# Create temporary file
temp_file=$(mktemp)

# Copy template to temp file
cp "$TEMPLATE_FILE" "$temp_file"

# Replace placeholders
print_info "Customizing configuration..."

# Replace domain name
sed -i.bak "s/example\.com/$domain_name/g" "$temp_file"
sed -i.bak "s/server_name.*;/server_name $server_name;/" "$temp_file"

# Replace SSL paths
sed -i.bak "s|ssl_certificate .*;|ssl_certificate $ssl_cert;|" "$temp_file"
sed -i.bak "s|ssl_certificate_key .*;|ssl_certificate_key $ssl_key;|" "$temp_file"

# Replace backend URL (for reverse proxy and SSL termination)
if [[ "$CONFIG_NAME" == "reverse-proxy" || "$CONFIG_NAME" == "ssl-termination" ]]; then
    sed -i.bak "s|proxy_pass .*localhost:3000;|proxy_pass http://$backend_url;|" "$temp_file"
    sed -i.bak "s|proxy_pass .*internal-backend:8080;|proxy_pass http://$backend_url;|" "$temp_file"
fi

# Replace backends (for load balancer)
if [[ "$CONFIG_NAME" == "load-balancer" ]]; then
    # Create upstream block
    upstream_block="upstream backend {\n    least_conn;\n"
    for backend in "${backends[@]}"; do
        upstream_block+="    server $backend max_fails=3 fail_timeout=30s weight=1;\n"
    done
    upstream_block+="    keepalive 32;\n    keepalive_requests 100;\n    keepalive_timeout 60s;\n}"

    # Replace the upstream block (this is simplified - in production you'd want more robust replacement)
    print_warning "Note: Backend servers need to be manually verified in the generated config"
fi

# Replace root directory (for static site)
if [[ "$CONFIG_NAME" == "static-site" ]]; then
    sed -i.bak "s|root /var/www/html;|root $root_dir;|" "$temp_file"
fi

# Remove backup files
rm -f "$temp_file.bak"

# Move to output file
mv "$temp_file" "$output_file"

print_success "Configuration generated: $output_file"

# ============================================================================
# Step 4: Display Summary and Next Steps
# ============================================================================

echo ""
print_header "Configuration Summary"

echo "Configuration Type: $CONFIG_DESC"
echo "Domain: $server_name"
echo "SSL Certificate: $ssl_cert"
echo "SSL Key: $ssl_key"

if [[ "$CONFIG_NAME" != "static-site" ]]; then
    if [[ "$CONFIG_NAME" == "load-balancer" ]]; then
        echo "Backend Servers: ${#backends[@]}"
        for backend in "${backends[@]}"; do
            echo "  - $backend"
        done
    else
        echo "Backend: $backend_url"
    fi
fi

if [[ "$CONFIG_NAME" == "static-site" ]]; then
    echo "Root Directory: $root_dir"
fi

echo "Output File: $output_file"

echo ""
print_header "Next Steps"

echo "1. Review the generated configuration:"
echo "   cat $output_file"
echo ""

echo "2. Customize any additional settings in the file if needed"
echo ""

echo "3. Test the configuration:"
echo "   sudo nginx -t -c $output_file"
echo ""

echo "4. Copy to Nginx sites-available:"
echo "   sudo cp $output_file /etc/nginx/sites-available/"
echo ""

echo "5. Create symbolic link to sites-enabled:"
echo "   sudo ln -s /etc/nginx/sites-available/$output_file /etc/nginx/sites-enabled/"
echo ""

echo "6. Reload Nginx:"
echo "   sudo systemctl reload nginx"
echo ""

echo "7. Verify the site is working:"
echo "   curl -I https://$domain_name"
echo ""

# SSL certificate generation reminder
if [[ ! -f "$ssl_cert" ]]; then
    print_warning "SSL certificate not found at: $ssl_cert"
    echo ""
    echo "To generate SSL certificate with Let's Encrypt:"
    echo "   sudo certbot certonly --nginx -d $domain_name"
    echo ""
fi

# Additional notes based on config type
case $CONFIG_NAME in
    "load-balancer")
        print_info "Load Balancer Notes:"
        echo "  - Verify backend servers are accessible"
        echo "  - Check health check endpoints"
        echo "  - Monitor backend distribution in logs"
        ;;
    "static-site")
        print_info "Static Site Notes:"
        echo "  - Ensure static files are in: $root_dir"
        echo "  - Set proper permissions: sudo chown -R www-data:www-data $root_dir"
        echo "  - For SPAs, ensure index.html exists"
        ;;
    "api-gateway")
        print_info "API Gateway Notes:"
        echo "  - Configure CORS origins in the config file"
        echo "  - Set up API key validation"
        echo "  - Review rate limiting settings"
        echo "  - Test with: curl -i https://$domain_name/health"
        ;;
esac

echo ""
print_success "Configuration generation complete!"
echo ""
