#!/bin/bash
# Fix Explorer Service Script
# Attempts to restore explorer functionality

set -e

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

# Configuration
EXPLORER_VMID=5000
EXPLORER_IP="192.168.11.140"
PROXMOX_HOST="192.168.11.10"

echo "=========================================="
echo "Explorer Service Fix Script"
echo "=========================================="
echo ""

# Function to check if we can access Proxmox host
check_proxmox_access() {
    if ssh -o ConnectTimeout=5 -o BatchMode=yes root@$PROXMOX_HOST "echo test" 2>/dev/null; then
        return 0
    else
        return 1
    fi
}

# Function to check container status
check_container() {
    if check_proxmox_access; then
        ssh root@$PROXMOX_HOST "pct status $EXPLORER_VMID 2>/dev/null | awk '{print \$2}'" 2>/dev/null
    else
        echo "unknown"
    fi
}

# Function to start container
start_container() {
    echo -e "${BLUE}Starting container VMID $EXPLORER_VMID...${NC}"
    if check_proxmox_access; then
        ssh root@$PROXMOX_HOST "pct start $EXPLORER_VMID" 2>&1
        sleep 5
        echo -e "${GREEN}Container start command executed${NC}"
    else
        echo -e "${YELLOW}⚠ Cannot access Proxmox host. Please run manually:${NC}"
        echo "   ssh root@$PROXMOX_HOST"
        echo "   pct start $EXPLORER_VMID"
        return 1
    fi
}

# Function to restart Blockscout service
restart_blockscout() {
    echo -e "${BLUE}Restarting Blockscout service...${NC}"
    if check_proxmox_access; then
        ssh root@$PROXMOX_HOST "pct exec $EXPLORER_VMID -- systemctl restart blockscout" 2>&1 || \
        ssh root@$PROXMOX_HOST "pct exec $EXPLORER_VMID -- cd /opt/blockscout && docker-compose restart" 2>&1 || \
        ssh root@$PROXMOX_HOST "pct exec $EXPLORER_VMID -- docker-compose -f /opt/blockscout/docker-compose.yml restart" 2>&1
        sleep 10
        echo -e "${GREEN}Blockscout restart command executed${NC}"
    else
        echo -e "${YELLOW}⚠ Cannot access Proxmox host. Please run manually:${NC}"
        echo "   ssh root@$PROXMOX_HOST"
        echo "   pct exec $EXPLORER_VMID -- systemctl restart blockscout"
    fi
}

# Function to restart Nginx
restart_nginx() {
    echo -e "${BLUE}Restarting Nginx...${NC}"
    if check_proxmox_access; then
        ssh root@$PROXMOX_HOST "pct exec $EXPLORER_VMID -- systemctl restart nginx" 2>&1
        sleep 3
        echo -e "${GREEN}Nginx restart command executed${NC}"
    else
        echo -e "${YELLOW}⚠ Cannot access Proxmox host. Please run manually:${NC}"
        echo "   ssh root@$PROXMOX_HOST"
        echo "   pct exec $EXPLORER_VMID -- systemctl restart nginx"
    fi
}

# Function to check Blockscout status
check_blockscout_status() {
    echo -e "${BLUE}Checking Blockscout status...${NC}"
    if check_proxmox_access; then
        echo "Container status:"
        ssh root@$PROXMOX_HOST "pct status $EXPLORER_VMID" 2>/dev/null || echo "Container not found"
        echo ""
        echo "Blockscout service:"
        ssh root@$PROXMOX_HOST "pct exec $EXPLORER_VMID -- systemctl status blockscout 2>/dev/null | head -10" || echo "Service check failed"
        echo ""
        echo "Docker containers:"
        ssh root@$PROXMOX_HOST "pct exec $EXPLORER_VMID -- docker ps 2>/dev/null" || echo "Docker check failed"
    else
        echo -e "${YELLOW}⚠ Cannot access Proxmox host${NC}"
    fi
}

# Main execution
echo "Step 1: Checking container status..."
CONTAINER_STATUS=$(check_container)
echo "Container status: $CONTAINER_STATUS"
echo ""

if [ "$CONTAINER_STATUS" != "running" ]; then
    echo -e "${YELLOW}Container is not running. Attempting to start...${NC}"
    start_container
    sleep 5
    CONTAINER_STATUS=$(check_container)
    if [ "$CONTAINER_STATUS" != "running" ]; then
        echo -e "${RED}✗ Failed to start container${NC}"
        echo "Please check manually:"
        echo "  ssh root@$PROXMOX_HOST"
        echo "  pct status $EXPLORER_VMID"
        exit 1
    fi
fi

echo -e "${GREEN}✓ Container is running${NC}"
echo ""

echo "Step 2: Checking Blockscout service..."
check_blockscout_status
echo ""

echo "Step 3: Restarting Blockscout service..."
restart_blockscout
echo ""

echo "Step 4: Restarting Nginx..."
restart_nginx
echo ""

echo "Step 5: Waiting for services to stabilize..."
sleep 15
echo ""

echo "Step 6: Testing Blockscout API..."
if timeout 5 bash -c "echo > /dev/tcp/$EXPLORER_IP/4000" 2>/dev/null; then
    API_RESPONSE=$(curl -s "http://$EXPLORER_IP:4000/api/v2/status" 2>&1)
    if echo "$API_RESPONSE" | grep -q "chain_id"; then
        echo -e "${GREEN}✓ Blockscout API is responding${NC}"
        echo "$API_RESPONSE" | head -5
    else
        echo -e "${YELLOW}⚠ Blockscout port is open but API not responding correctly${NC}"
        echo "Response: $API_RESPONSE"
    fi
else
    echo -e "${RED}✗ Blockscout port 4000 is still not accessible${NC}"
    echo "Please check logs:"
    echo "  ssh root@$PROXMOX_HOST"
    echo "  pct exec $EXPLORER_VMID -- journalctl -u blockscout -n 50"
    echo "  pct exec $EXPLORER_VMID -- docker-compose -f /opt/blockscout/docker-compose.yml logs"
fi
echo ""

echo "Step 7: Testing Nginx proxy..."
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "http://$EXPLORER_IP" 2>&1)
if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "301" ] || [ "$HTTP_CODE" = "302" ]; then
    echo -e "${GREEN}✓ Nginx is responding (HTTP $HTTP_CODE)${NC}"
else
    echo -e "${YELLOW}⚠ Nginx responding with HTTP $HTTP_CODE${NC}"
fi
echo ""

echo "=========================================="
echo "Fix Script Complete"
echo "=========================================="
echo ""
echo "Next steps:"
echo "1. Verify Blockscout is running: curl http://$EXPLORER_IP:4000/api/v2/status"
echo "2. Check Cloudflare tunnel configuration"
echo "3. Verify DNS record for explorer.d-bis.org"
echo "4. Test public URL: curl https://explorer.d-bis.org"

