#!/bin/bash
# Start Blockscout using Proxmox API
# Works when container is on any node

set -e

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

# Colors
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"; }

echo ""
log_info "Starting Blockscout via Proxmox API"
log_info "VMID: $VMID"
echo ""

# Find which node has the container
log_info "Finding container location..."
for node in ml110 pve pve2; do
    STATUS=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
        "pvesh get /nodes/$node/lxc/$VMID/status/current --output-format json 2>/dev/null | grep -o '\"status\":\"[^\"]*\"' | head -1" 2>&1)
    if echo "$STATUS" | grep -q "status"; then
        CONTAINER_NODE="$node"
        CONTAINER_STATUS=$(echo "$STATUS" | grep -o '"[^"]*"' | tail -1 | tr -d '"')
        log_success "Container found on node: $CONTAINER_NODE (status: $CONTAINER_STATUS)"
        break
    fi
done

if [ -z "$CONTAINER_NODE" ]; then
    log_warn "Container not found on any node"
    exit 1
fi

# Ensure container is running
if [ "$CONTAINER_STATUS" != "running" ]; then
    log_info "Starting container..."
    ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
        "pvesh create /nodes/$CONTAINER_NODE/lxc/$VMID/status/start" 2>&1
    sleep 5
fi

# Try multiple methods to start Blockscout
log_info "Attempting to start Blockscout service..."

# Method 1: systemd service
log_info "Method 1: Starting via systemd..."
ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
    "pvesh create /nodes/$CONTAINER_NODE/lxc/$VMID/exec \
    --command 'systemctl start blockscout && sleep 3 && systemctl status blockscout --no-pager -l' \
    --output-format json 2>&1" | grep -E "status|Active|Failed" || true

sleep 5

# Method 2: docker-compose
log_info "Method 2: Starting via docker-compose..."
ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
    "pvesh create /nodes/$CONTAINER_NODE/lxc/$VMID/exec \
    --command 'cd /opt/blockscout && docker-compose up -d 2>&1 || docker compose up -d 2>&1' \
    --output-format json 2>&1" | grep -v "^{" | grep -v "^}$" || true

sleep 10

# Check status
log_info "Checking Blockscout status..."
API_RESPONSE=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
    "pvesh create /nodes/$CONTAINER_NODE/lxc/$VMID/exec \
    --command 'timeout 10 curl -s http://127.0.0.1:4000/api/v2/status 2>&1' \
    --output-format json 2>&1" | grep -o '"data":"[^"]*"' | sed 's/"data":"//;s/"$//' | head -1)

if echo "$API_RESPONSE" | grep -q "chain_id\|success"; then
    log_success "Blockscout is responding!"
    echo "$API_RESPONSE" | head -5
else
    log_warn "Blockscout may still be starting..."
    echo "Response: $API_RESPONSE"
fi

echo ""
log_info "Startup complete. Test with:"
echo "  curl http://192.168.11.140:4000/api/v2/status"

