#!/usr/bin/env bash
# Deploy Explorer to Production
# Copies frontend files to the Blockscout container

set -euo pipefail

IP="${IP:-192.168.11.140}"
DOMAIN="${DOMAIN:-explorer.d-bis.org}"
PASSWORD="${PASSWORD:-L@kers2010}"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_step() { echo -e "${CYAN}[STEP]${NC} $1"; }

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "════════════════════════════════════════════════════════"
echo "Deploy Chain 138 Explorer to Production"
echo "════════════════════════════════════════════════════════"
echo ""

# Check if files exist
if [ ! -f "$REPO_ROOT/frontend/public/index.html" ]; then
    log_error "Frontend file not found: $REPO_ROOT/frontend/public/index.html"
    exit 1
fi

log_step "Step 1: Backing up current deployment..."
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"

log_success "Backup created"

log_step "Step 2: Deploying frontend files..."
sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no \
    "$REPO_ROOT/frontend/public/index.html" \
    root@"$IP":/var/www/html/index.html
[ -f "$REPO_ROOT/frontend/public/explorer-spa.js" ] && sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no \
    "$REPO_ROOT/frontend/public/explorer-spa.js" \
    root@"$IP":/var/www/html/explorer-spa.js

log_success "Frontend deployed"

log_step "Step 3: Verifying deployment..."
sleep 2
if curl -k -sI "https://$DOMAIN/" 2>&1 | grep -qi "HTTP.*200"; then
    log_success "Deployment verified - Explorer is accessible"
else
    log_warn "Deployment completed but verification failed - check manually"
fi

echo ""
log_success "Deployment complete!"
echo ""
log_info "Explorer URL: https://$DOMAIN/"
log_info "To rollback: ssh root@$IP 'cp /var/www/html/index.html.backup.* /var/www/html/index.html'"
echo ""

