#!/bin/bash
#
# Reverse Proxy Setup (Nginx/Caddy)
#

setup_nginx() {
    log_info "Setting up Nginx reverse proxy..."
    
    # Install Nginx if not installed
    if ! command_exists nginx; then
        apt-get install -y nginx
    fi
    
    # Create Nginx configuration
    cat > /etc/nginx/sites-available/calypso <<EOF
server {
    listen 80;
    server_name _;
    
    # Redirect to HTTPS (if SSL is configured)
    # return 301 https://\$server_name\$request_uri;
    
    # For development, serve HTTP directly
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
        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;
    }
    
    location /api {
        proxy_pass http://localhost:8080;
        proxy_http_version 1.1;
        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;
    }
    
    location /ws {
        proxy_pass http://localhost:8080;
        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;
    }
}
EOF
    
    # Enable site
    ln -sf /etc/nginx/sites-available/calypso /etc/nginx/sites-enabled/
    rm -f /etc/nginx/sites-enabled/default
    
    # Test and reload
    nginx -t && systemctl reload nginx
    
    log_info "✓ Nginx reverse proxy configured"
}

setup_caddy() {
    log_info "Setting up Caddy reverse proxy..."
    
    # Install Caddy if not installed
    if ! command_exists caddy; then
        apt-get install -y debian-keyring debian-archive-keyring apt-transport-https
        curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
        curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list
        apt-get update
        apt-get install -y caddy
    fi
    
    # Create Caddyfile
    cat > /etc/caddy/Caddyfile <<EOF
:80 {
    reverse_proxy /api localhost:8080
    reverse_proxy /ws localhost:8080 {
        header_up Connection "Upgrade"
        header_up Upgrade "websocket"
    }
    reverse_proxy / localhost:3000
}
EOF
    
    # Reload Caddy
    systemctl reload caddy
    
    log_info "✓ Caddy reverse proxy configured"
}

