#!/bin/bash
# Fix Nginx Proxy Configuration
# Run this script on the Nginx proxy VM to fix common issues

set -euo pipefail

echo "=========================================="
echo "Fixing Nginx Proxy Configuration"
echo "=========================================="
echo ""

# Check if running as root or with sudo
if [ "$EUID" -ne 0 ]; then
    echo "This script requires sudo privileges"
    exit 1
fi

# Install missing packages
echo "1. Installing missing packages..."
apt-get update -qq

# Install Docker if not present
if ! command -v docker &> /dev/null; then
    echo "Installing Docker..."
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
    apt-get update -qq
    apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
    systemctl enable docker
    systemctl start docker
    echo "Docker installed"
else
    echo "Docker already installed"
fi

# Install Cloudflared if not present
if ! command -v cloudflared &> /dev/null; then
    echo "Installing Cloudflared..."
    curl -L --output /tmp/cloudflared.deb https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
    dpkg -i /tmp/cloudflared.deb || apt-get install -f -y
    rm /tmp/cloudflared.deb
    echo "Cloudflared installed"
else
    echo "Cloudflared already installed"
fi

# Fix Nginx configuration
echo ""
echo "2. Fixing Nginx configuration..."

# Create directories
mkdir -p /var/www/html
mkdir -p /etc/nginx/conf.d

# Check Nginx config
if nginx -t 2>&1 | grep -q "syntax is ok"; then
    echo "Nginx configuration is valid"
    
    # Try to start Nginx
    if systemctl start nginx 2>/dev/null; then
        echo "Nginx started successfully"
        systemctl enable nginx
    else
        echo "Nginx failed to start. Checking logs..."
        journalctl -u nginx --no-pager -n 20
    fi
else
    echo "Nginx configuration has errors:"
    nginx -t
    echo ""
    echo "Creating minimal working configuration..."
    
    # Create minimal Nginx config
    cat > /etc/nginx/nginx.conf <<'EOF'
user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    
    sendfile on;
    keepalive_timeout 65;
    
    server {
        listen 80;
        server_name _;
        
        location / {
            return 200 "Nginx Proxy - Phase 1\n";
            add_header Content-Type text/plain;
        }
        
        location /health {
            return 200 "healthy\n";
            add_header Content-Type text/plain;
        }
    }
}
EOF
    
    if nginx -t; then
        systemctl start nginx
        systemctl enable nginx
        echo "Nginx started with minimal configuration"
    else
        echo "Failed to create valid Nginx configuration"
    fi
fi

# Check service status
echo ""
echo "3. Service Status:"
systemctl is-active nginx && echo "✓ Nginx: active" || echo "✗ Nginx: inactive"
systemctl is-active docker && echo "✓ Docker: active" || echo "✗ Docker: inactive"
systemctl is-active cloudflared && echo "✓ Cloudflared: active" || echo "⊘ Cloudflared: inactive (not configured)"

echo ""
echo "=========================================="
echo "Nginx Proxy Fix Complete"
echo "=========================================="

