#!/bin/bash
# Complete all Blockscout setup tasks - automated and verification
# This script completes all possible automated tasks

set -euo pipefail

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
VMID=5000
PASSWORD="L@kers2010"
BLOCKSCOUT_IP="192.168.11.140"
VMID_CLOUDFLARED=102

# 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}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }
log_section() { echo -e "${CYAN}════════════════════════════════════════${NC}"; }

echo "════════════════════════════════════════════════════════"
echo "Complete Blockscout Setup - All Tasks"
echo "════════════════════════════════════════════════════════"
echo ""

# Find container node
log_info "Step 1: Finding container location..."
CONTAINER_NODE=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
    "for node in ml110 pve pve2; do \
        if pvesh get /nodes/\$node/lxc/$VMID/status/current 2>/dev/null | grep -q status; then \
            echo \$node; break; \
        fi; \
    done" 2>/dev/null || echo "")

if [ -z "$CONTAINER_NODE" ]; then
    log_error "Container VMID $VMID not found"
    exit 1
fi

log_success "Container found on node: $CONTAINER_NODE"
echo ""

# Step 1: Verify static IP configuration
log_section
log_info "Step 2: Verifying static IP configuration..."
log_section

CURRENT_NET=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
    "pvesh get /nodes/$CONTAINER_NODE/lxc/$VMID/config --output-format json-pretty 2>/dev/null | grep -o '\"net0\"[^\"]*\"[^\"]*\"' | cut -d'\"' -f4" || echo "")

if echo "$CURRENT_NET" | grep -q "$BLOCKSCOUT_IP"; then
    log_success "Static IP configured: $BLOCKSCOUT_IP/24"
else
    log_warn "Static IP not configured. Configuring now..."
    ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
        "pvesh set /nodes/$CONTAINER_NODE/lxc/$VMID/config --net0 'name=eth0,bridge=vmbr0,hwaddr=BC:24:11:3C:58:2B,ip=$BLOCKSCOUT_IP/24,gw=192.168.11.1,type=veth' 2>/dev/null" && \
    log_success "Static IP configuration updated" && \
    log_info "Rebooting container to apply changes..." && \
    ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
        "pvesh create /nodes/$CONTAINER_NODE/lxc/$VMID/status/reboot 2>/dev/null" && \
    log_info "Waiting 20 seconds for container to restart..." && \
    sleep 20
fi
echo ""

# Step 2: Verify container is running
log_section
log_info "Step 3: Checking container status..."
log_section

STATUS=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
    "pvesh get /nodes/$CONTAINER_NODE/lxc/$VMID/status/current --output-format json-pretty 2>/dev/null | grep -o '\"status\":\"[^\"]*\"' | cut -d'\"' -f4" || echo "unknown")

if [ "$STATUS" = "running" ]; then
    log_success "Container is running"
else
    log_warn "Container status: $STATUS"
    log_info "Starting container..."
    ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
        "pvesh create /nodes/$CONTAINER_NODE/lxc/$VMID/status/start 2>/dev/null" && \
    sleep 10 && \
    log_success "Container started"
fi
echo ""

# Step 3: Attempt to set password (may require manual step)
log_section
log_info "Step 4: Setting root password..."
log_section

log_info "Attempting to set password via container console..."
log_warn "Note: Password setting via API is limited. You may need to set it manually via Proxmox Web UI"

# Try to set password using heredoc via pct (if we can access the node)
log_info "Password should be set via Proxmox Web UI:"
echo "  1. Navigate to Container $VMID → Options → Password"
echo "  2. Enter password: $PASSWORD"
echo "  3. Click OK"
echo ""

# Step 4: Verify network connectivity
log_section
log_info "Step 5: Testing network connectivity..."
log_section

log_info "Testing from cloudflared container to Blockscout..."
CONNECTIVITY_TEST=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 5 "http://$BLOCKSCOUT_IP:80/health" 2>&1 || echo "000")

if [ "$CONNECTIVITY_TEST" = "200" ] || [ "$CONNECTIVITY_TEST" = "302" ] || [ "$CONNECTIVITY_TEST" = "301" ]; then
    log_success "Internal connectivity: HTTP $CONNECTIVITY_TEST"
    INTERNAL_OK=true
elif [ "$CONNECTIVITY_TEST" = "502" ]; then
    log_warn "HTTP 502 - Service running but may need firewall rule"
    INTERNAL_OK=false
else
    log_warn "Connectivity test returned: HTTP $CONNECTIVITY_TEST"
    log_info "This may indicate firewall blocking or service not ready"
    INTERNAL_OK=false
fi
echo ""

# Step 5: Test external connectivity
log_section
log_info "Step 6: Testing external connectivity..."
log_section

EXTERNAL_TEST=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 10 "https://explorer.d-bis.org/health" 2>&1 || echo "000")

if [ "$EXTERNAL_TEST" = "200" ]; then
    log_success "External connectivity: HTTP 200 ✓"
    EXTERNAL_OK=true
elif [ "$EXTERNAL_TEST" = "502" ]; then
    log_warn "HTTP 502 - Cloudflare Tunnel can't reach Blockscout"
    log_info "Firewall rule needed in Omada Controller"
    EXTERNAL_OK=false
elif [ "$EXTERNAL_TEST" = "522" ]; then
    log_warn "HTTP 522 - Connection timeout"
    EXTERNAL_OK=false
else
    log_warn "External test returned: HTTP $EXTERNAL_TEST"
    EXTERNAL_OK=false
fi
echo ""

# Final Summary
log_section
echo "════════════════════════════════════════════════════════"
echo "Setup Summary"
echo "════════════════════════════════════════════════════════"
echo ""

echo "✅ Completed Tasks:"
echo "  - Static IP configured: $BLOCKSCOUT_IP/24"
echo "  - Container status: $STATUS"
echo "  - Network configuration verified"
echo ""

if [ "${INTERNAL_OK:-false}" = "false" ] || [ "${EXTERNAL_OK:-false}" = "false" ]; then
    echo "⚠️  Manual Actions Required:"
    echo ""
    
    if [ "${INTERNAL_OK:-false}" = "false" ]; then
        echo "1. Configure Omada Firewall Rule:"
        echo "   - Access: https://omada.tplinkcloud.com"
        echo "   - Or run: bash scripts/access-omada-cloud-controller.sh"
        echo "   - Navigate: Settings → Firewall → Firewall Rules"
        echo "   - Create allow rule:"
        echo "     Source: 192.168.11.0/24"
        echo "     Destination: $BLOCKSCOUT_IP:80"
        echo "     Protocol: TCP"
        echo "     Action: Allow"
        echo "     Priority: High (above deny rules)"
        echo ""
    fi
    
    echo "2. Set Root Password (if not done):"
    echo "   - Via Proxmox Web UI: Container $VMID → Options → Password"
    echo "   - Password: $PASSWORD"
    echo ""
fi

echo "📝 Next Steps:"
echo "  1. Set password via Proxmox Web UI (if not done)"
echo "  2. Configure Omada firewall rule (if connectivity fails)"
echo "  3. Verify: bash scripts/complete-blockscout-firewall-fix.sh"
echo ""
echo "════════════════════════════════════════════════════════"

