#!/usr/bin/env bash
# Simple deployment script for blockscout frontend
# Usage: ./deploy-blockscout-frontend.sh [VMID] [IP]

set -euo pipefail

VMID="${1:-5000}"
IP="${2:-192.168.11.140}"
PASSWORD="${PASSWORD:-L@kers2010}"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
FRONTEND_FILE="$PROJECT_ROOT/explorer-monorepo/frontend/public/index.html"

if [ ! -f "$FRONTEND_FILE" ]; then
    echo "ERROR: Frontend file not found: $FRONTEND_FILE"
    exit 1
fi

echo "Deploying blockscout frontend..."
echo "VMID: $VMID"
echo "IP: $IP"
echo ""

# Create backup
echo "Creating backup..."
sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" \
    "cp /var/www/html/index.html /var/www/html/index.html.backup.\$(date +%Y%m%d_%H%M%S) 2>/dev/null || true"

# Deploy file
echo "Deploying frontend..."
sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no "$FRONTEND_FILE" "root@$IP:/var/www/html/index.html"

# Verify
echo "Verifying deployment..."
if sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" \
    "grep -q 'unpkg.com' /var/www/html/index.html 2>/dev/null"; then
    echo "✅ Deployment successful - fallback CDN detected"
else
    echo "⚠️  Deployment completed but verification failed"
fi

# Reload nginx
echo "Reloading nginx..."
sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "systemctl reload nginx"

echo ""
echo "✅ Deployment complete!"
echo "Frontend is now live at: https://explorer.d-bis.org"

