#!/bin/bash
set -e

if [ "$EUID" -ne 0 ]; then 
  echo "Please run as root (sudo)"
  exit 1
fi

echo "--- Installing Nginx ---"
apt-get update
apt-get install -y nginx

echo "--- Configuring Reverse Proxy ---"
# Remove default config if it exists
if [ -f /etc/nginx/sites-enabled/default ]; then
    unlink /etc/nginx/sites-enabled/default || rm /etc/nginx/sites-enabled/default
fi

# Create new config
cat > /etc/nginx/sites-available/wa-bot-proxy << 'EOF'
server {
    listen 80;
    server_name wa.app.oncloud.my.id;

    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;
    }
}
EOF

# Enable site
ln -sf /etc/nginx/sites-available/wa-bot-proxy /etc/nginx/sites-enabled/

echo "--- Verifying Nginx Configuration ---"
nginx -t

echo "--- Reloading Nginx ---"
systemctl reload nginx

echo "--- Nginx Setup Complete! ---"
