#!/bin/bash
# configure-nginx-proxy.sh
# Configuration script for Nginx Proxy VM

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

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

log() {
    echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $*"
}

log_success() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] ✅${NC} $*"
}

log_warning() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] ⚠️${NC} $*"
}

log_error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ❌${NC} $*"
}

# Get VM IP address
get_vm_ip() {
    local vm_name=$1
    local ip
    
    ip=$(kubectl get proxmoxvm "${vm_name}" -n default -o jsonpath='{.status.ipAddress}' 2>/dev/null || echo "")
    
    if [ -z "${ip}" ] || [ "${ip}" = "<none>" ]; then
        log_warning "VM IP not yet assigned. Waiting..."
        return 1
    fi
    
    echo "${ip}"
}

# Wait for VM to be ready
wait_for_vm() {
    local vm_name=$1
    local max_attempts=30
    local attempt=0
    
    log "Waiting for ${vm_name} to be ready..."
    
    while [ ${attempt} -lt ${max_attempts} ]; do
        local ip
        ip=$(get_vm_ip "${vm_name}" 2>/dev/null || echo "")
        
        if [ -n "${ip}" ] && [ "${ip}" != "<none>" ]; then
            log_success "${vm_name} is ready at ${ip}"
            echo "${ip}"
            return 0
        fi
        
        attempt=$((attempt + 1))
        sleep 10
    done
    
    log_error "${vm_name} did not become ready in time"
    return 1
}

# Generate Nginx configuration
generate_nginx_config() {
    local config_file=$1
    local domain=$2
    local backend_ip=$3
    local backend_port=${4:-80}
    
    cat > "${config_file}" <<EOF
server {
    listen 80;
    listen [::]:80;
    server_name ${domain};
    
    # Redirect HTTP to HTTPS
    return 301 https://\$server_name\$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ${domain};
    
    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/${domain}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${domain}/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    
    # Security Headers
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    
    # Logging
    access_log /var/log/nginx/${domain}-access.log;
    error_log /var/log/nginx/${domain}-error.log;
    
    # Proxy Settings
    location / {
        proxy_pass http://${backend_ip}:${backend_port};
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
        proxy_read_timeout 300s;
        proxy_connect_timeout 75s;
    }
}
EOF
}

main() {
    log "=========================================="
    log "Nginx Proxy Configuration Script"
    log "=========================================="
    log ""
    
    # Check if VM exists
    if ! kubectl get proxmoxvm nginx-proxy-vm -n default &>/dev/null; then
        log_error "nginx-proxy-vm not found. Please deploy it first."
        exit 1
    fi
    
    # Wait for VM to be ready
    local vm_ip
    vm_ip=$(wait_for_vm "nginx-proxy-vm")
    
    if [ -z "${vm_ip}" ]; then
        log_error "Failed to get VM IP address"
        exit 1
    fi
    
    log_success "Nginx Proxy VM is ready at ${vm_ip}"
    log ""
    log "Next steps:"
    log "1. SSH into the VM: ssh admin@${vm_ip}"
    log "2. Install SSL certificates using certbot:"
    log "   sudo certbot --nginx -d your-domain.com"
    log "3. Configure backend services in /etc/nginx/sites-available/"
    log "4. Test configuration: sudo nginx -t"
    log "5. Reload nginx: sudo systemctl reload nginx"
    log ""
    log "Example Nginx configuration files are available in:"
    log "  ${PROJECT_ROOT}/docs/configs/nginx/"
    log ""
}

main "$@"

