#!/bin/bash
# Start Blockscout Service in Container VMID 5000
# Attempts multiple methods to start Blockscout

set -e

VMID="${1:-5000}"
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
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"; }

echo ""
log_info "Starting Blockscout Service"
log_info "VMID: $VMID"
log_info "Proxmox Host: $PROXMOX_HOST"
echo ""

# Function to execute command in container
exec_container() {
    ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@"$PROXMOX_HOST" "pct exec $VMID -- bash -c '$1'" 2>&1
}

# Check if we can access Proxmox host
log_info "Step 1: Checking Proxmox host access..."
if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "echo test" 2>/dev/null; then
    log_success "Proxmox host is accessible"
else
    log_error "Cannot access Proxmox host: $PROXMOX_HOST"
    log_info "Please ensure SSH access is configured:"
    echo "  ssh root@$PROXMOX_HOST"
    exit 1
fi

# Check container status
log_info "Step 2: Checking container status..."
CONTAINER_STATUS=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct status $VMID 2>/dev/null | awk '{print \$2}'" || echo "unknown")
if [ "$CONTAINER_STATUS" != "running" ]; then
    log_warn "Container is not running (status: $CONTAINER_STATUS)"
    log_info "Starting container..."
    ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct start $VMID" 2>&1
    sleep 5
    CONTAINER_STATUS=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct status $VMID 2>/dev/null | awk '{print \$2}'" || echo "unknown")
    if [ "$CONTAINER_STATUS" = "running" ]; then
        log_success "Container started"
    else
        log_error "Failed to start container"
        exit 1
    fi
else
    log_success "Container is running"
fi

# Check current Blockscout status
log_info "Step 3: Checking current Blockscout status..."
SERVICE_STATUS=$(exec_container "systemctl is-active blockscout 2>/dev/null || echo 'inactive'")
if [ "$SERVICE_STATUS" = "active" ]; then
    log_success "Blockscout service is already active"
    PORT_CHECK=$(exec_container "ss -tlnp | grep :4000 || echo 'not_listening'")
    if echo "$PORT_CHECK" | grep -q ":4000"; then
        log_success "Port 4000 is listening"
        API_TEST=$(exec_container "timeout 5 curl -s http://127.0.0.1:4000/api/v2/status 2>&1" || echo "FAILED")
        if echo "$API_TEST" | grep -q "chain_id\|success"; then
            log_success "Blockscout API is responding"
            echo "$API_TEST" | head -5
            exit 0
        else
            log_warn "Service active but API not responding correctly"
        fi
    else
        log_warn "Service active but port 4000 not listening"
    fi
else
    log_warn "Blockscout service is $SERVICE_STATUS"
fi

# Try to start Blockscout service
log_info "Step 4: Attempting to start Blockscout service..."

# Method 1: systemd service
log_info "Trying systemd service..."
exec_container "systemctl start blockscout" && sleep 5
SERVICE_STATUS=$(exec_container "systemctl is-active blockscout 2>/dev/null || echo 'inactive'")
if [ "$SERVICE_STATUS" = "active" ]; then
    log_success "Blockscout service started via systemd"
else
    log_warn "systemd service start failed, trying docker-compose..."
    
    # Method 2: docker-compose
    log_info "Trying docker-compose..."
    if exec_container "test -f /opt/blockscout/docker-compose.yml"; then
        exec_container "cd /opt/blockscout && docker-compose up -d" 2>&1 || \
        exec_container "cd /opt/blockscout && docker compose up -d" 2>&1
        sleep 10
        log_info "Waiting for containers to start..."
    else
        log_warn "docker-compose.yml not found at /opt/blockscout/"
    fi
    
    # Method 3: Check for docker containers
    log_info "Checking for existing Docker containers..."
    DOCKER_CONTAINERS=$(exec_container "docker ps -a | grep blockscout || echo 'none'")
    if echo "$DOCKER_CONTAINERS" | grep -q "blockscout"; then
        log_info "Found Blockscout containers, attempting to start..."
        exec_container "docker start \$(docker ps -a | grep blockscout | awk '{print \$1}')" 2>&1 || true
        sleep 10
    fi
fi

# Wait a bit for service to initialize
log_info "Step 5: Waiting for Blockscout to initialize..."
sleep 15

# Verify Blockscout is running
log_info "Step 6: Verifying Blockscout is running..."

# Check port
PORT_CHECK=$(exec_container "ss -tlnp | grep :4000 || echo 'not_listening'")
if echo "$PORT_CHECK" | grep -q ":4000"; then
    log_success "Port 4000 is now listening"
    echo "$PORT_CHECK"
else
    log_warn "Port 4000 is still not listening"
    log_info "Checking service logs..."
    exec_container "journalctl -u blockscout -n 20 --no-pager" || true
    exec_container "docker-compose -f /opt/blockscout/docker-compose.yml logs --tail=20 2>/dev/null" || true
fi

# Test API
log_info "Step 7: Testing Blockscout API..."
API_RESPONSE=$(exec_container "timeout 10 curl -s http://127.0.0.1:4000/api/v2/status 2>&1" || echo "FAILED")
if echo "$API_RESPONSE" | grep -q "chain_id\|success"; then
    log_success "Blockscout API is responding!"
    echo ""
    echo "API Response:"
    echo "$API_RESPONSE" | head -10
    echo ""
else
    log_warn "Blockscout API is not responding yet"
    echo "Response: $API_RESPONSE"
    echo ""
    log_info "Blockscout may need more time to start. This can take 1-2 minutes."
    log_info "Check status with: pct exec $VMID -- systemctl status blockscout"
fi

# Check from external
log_info "Step 8: Testing external access..."
EXTERNAL_IP="192.168.11.140"
if timeout 3 bash -c "echo > /dev/tcp/$EXTERNAL_IP/4000" 2>/dev/null; then
    log_success "Port 4000 is accessible externally"
    EXTERNAL_API=$(curl -s "http://$EXTERNAL_IP:4000/api/v2/status" 2>&1)
    if echo "$EXTERNAL_API" | grep -q "chain_id\|success"; then
        log_success "External API access working!"
    else
        log_warn "Port accessible but API response unexpected"
    fi
else
    log_warn "Port 4000 not accessible externally (may be firewall)"
fi

echo ""
log_info "Blockscout startup attempt complete!"
log_info "If service is still not running, check logs:"
echo "  pct exec $VMID -- journalctl -u blockscout -n 50"
echo "  pct exec $VMID -- docker-compose -f /opt/blockscout/docker-compose.yml logs"

