#!/bin/bash
# Start Blockscout from pve2 node
# Run this ON pve2 node

set -e

VMID=5000

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

# Check container status
log_info "Step 1: Checking container status..."
CONTAINER_STATUS=$(pct status $VMID 2>/dev/null | awk '{print $2}' || echo "unknown")
if [ "$CONTAINER_STATUS" != "running" ]; then
    log_warn "Container is not running. Starting..."
    pct start $VMID
    sleep 5
else
    log_success "Container is running"
fi

# Check Blockscout service
log_info "Step 2: Checking Blockscout service status..."
SERVICE_STATUS=$(pct exec $VMID -- systemctl is-active blockscout 2>/dev/null || echo "inactive")
log_info "Service status: $SERVICE_STATUS"

# Check if docker-compose exists
log_info "Step 3: Checking Blockscout installation..."
if pct exec $VMID -- test -f /opt/blockscout/docker-compose.yml 2>/dev/null; then
    log_success "Found docker-compose.yml at /opt/blockscout"
    BLOCKSCOUT_DIR="/opt/blockscout"
elif pct exec $VMID -- test -d /opt/blockscout 2>/dev/null; then
    log_info "Found /opt/blockscout directory"
    BLOCKSCOUT_DIR="/opt/blockscout"
else
    log_warn "Blockscout directory not found at /opt/blockscout"
    BLOCKSCOUT_DIR=""
fi

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

# Method 1: systemd service
log_info "Trying systemd service..."
pct exec $VMID -- systemctl start blockscout 2>&1 || log_warn "systemd start failed"
sleep 3

SERVICE_STATUS=$(pct exec $VMID -- 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 not active, trying docker-compose..."
    
    # Method 2: docker-compose
    if [ -n "$BLOCKSCOUT_DIR" ]; then
        log_info "Starting via docker-compose..."
        pct exec $VMID -- bash -c "cd $BLOCKSCOUT_DIR && docker-compose up -d 2>&1" || \
        pct exec $VMID -- bash -c "cd $BLOCKSCOUT_DIR && docker compose up -d 2>&1" || \
        log_warn "docker-compose start failed"
        sleep 10
    fi
    
    # Method 3: Check for existing containers
    log_info "Checking for existing Docker containers..."
    CONTAINERS=$(pct exec $VMID -- docker ps -a 2>/dev/null | grep blockscout || echo "")
    if [ -n "$CONTAINERS" ]; then
        log_info "Found Blockscout containers, starting them..."
        pct exec $VMID -- docker ps -a | grep blockscout | awk '{print $1}' | while read cid; do
            pct exec $VMID -- docker start $cid 2>&1 || true
        done
        sleep 10
    fi
fi

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

# Check port 4000
log_info "Step 6: Checking port 4000..."
PORT_CHECK=$(pct exec $VMID -- ss -tlnp 2>/dev/null | grep :4000 || echo "not_listening")
if echo "$PORT_CHECK" | grep -q ":4000"; then
    log_success "Port 4000 is listening"
    echo "$PORT_CHECK"
else
    log_warn "Port 4000 is not listening yet"
fi

# Test API
log_info "Step 7: Testing Blockscout API..."
API_RESPONSE=$(pct exec $VMID -- 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 "Checking service logs..."
    pct exec $VMID -- journalctl -u blockscout -n 20 --no-pager 2>&1 | head -20 || true
    echo ""
    if [ -n "$BLOCKSCOUT_DIR" ]; then
        log_info "Checking docker-compose logs..."
        pct exec $VMID -- bash -c "cd $BLOCKSCOUT_DIR && docker-compose logs --tail=20 2>&1" | head -30 || true
    fi
fi

# Check from container IP
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!"
    fi
else
    log_warn "Port 4000 not accessible externally (may need firewall rule)"
fi

echo ""
log_info "Startup attempt complete!"
echo ""
log_info "If Blockscout is still not running, check:"
echo "  pct exec $VMID -- systemctl status blockscout"
echo "  pct exec $VMID -- journalctl -u blockscout -n 50"
if [ -n "$BLOCKSCOUT_DIR" ]; then
    echo "  pct exec $VMID -- cd $BLOCKSCOUT_DIR && docker-compose logs"
fi

