#!/bin/bash
echo "=== CODE-SERVER NGINX + FROSTWALL DEPLOYMENT ==="
echo "Started: $(date)"
echo ""

# Step 1: Create Nginx site config
echo "--- Step 1: Create Nginx Config ---"
cat > /etc/nginx/sites-available/code.firefrostgaming.com << 'NGINX'
server {
    listen 74.63.218.202:80;
    server_name code.firefrostgaming.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        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;

        # WebSocket support (critical for Code-Server)
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        # Timeout settings for long sessions
        proxy_read_timeout 86400s;
        proxy_send_timeout 86400s;
    }
}
NGINX
echo "✓ Nginx config created"
echo ""

# Step 2: Enable site
echo "--- Step 2: Enable Site ---"
ln -sf /etc/nginx/sites-available/code.firefrostgaming.com /etc/nginx/sites-enabled/
echo "✓ Symlink created"
echo ""

# Step 3: Test Nginx config
echo "--- Step 3: Test Nginx Config ---"
nginx -t
echo ""

# Step 4: Restart Nginx (full restart for new IP binding)
echo "--- Step 4: Restart Nginx ---"
systemctl restart nginx
sleep 2
echo "✓ Nginx restarted"
echo ""

# Step 5: Verify Nginx binding to 202
echo "--- Step 5: Verify Nginx Binding ---"
ss -tlnp | grep 74.63.218.202
echo ""

# Step 6: Frostwall rules
echo "--- Step 6: Frostwall Rules ---"
ufw allow in on ens3 to 74.63.218.202 port 80 proto tcp comment "Code-Server HTTP"
ufw allow in on ens3 to 74.63.218.202 port 443 proto tcp comment "Code-Server HTTPS"
ufw reload
echo "✓ Frostwall rules applied"
echo ""

# Step 7: Verify Frostwall
echo "--- Step 7: Verify Frostwall ---"
ufw status numbered | grep 218.202
echo ""

# Step 8: Test HTTP response
echo "--- Step 8: Test HTTP Response ---"
curl -I http://code.firefrostgaming.com 2>/dev/null | head -10
echo ""

echo "=== NGINX DEPLOYMENT COMPLETE ==="
echo "Finished: $(date)"
echo ""
echo "NEXT MANUAL STEP:"
echo "Run: certbot --nginx -d code.firefrostgaming.com"
echo "Email: mkrause612@gmail.com"
echo "Terms: Y | Share: N | Redirect: 2 (Yes)"

exit 0
