#!/bin/bash
# Configure and start Blockscout with correct settings
# Run this INSIDE the Blockscout container (VMID 5000)

set -euo pipefail

# Configuration
CHAIN_ID=138
RPC_URL="http://192.168.11.250:8545"
WS_URL="ws://192.168.11.250:8546"
BLOCKSCOUT_HOST="192.168.11.140"
DB_PASSWORD="${DB_PASSWORD:-blockscout}"

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
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 "════════════════════════════════════════════════════════"
echo "Blockscout Configuration and Startup"
echo "════════════════════════════════════════════════════════"
echo ""
echo "Configuration:"
echo "  Chain ID: $CHAIN_ID"
echo "  RPC URL: $RPC_URL"
echo "  WS URL: $WS_URL"
echo "  Host: $BLOCKSCOUT_HOST"
echo ""

# Step 1: Check Docker
log_info "Step 1: Checking Docker..."
if ! command -v docker &> /dev/null; then
    log_error "Docker not found. Installing..."
    apt-get update -qq
    apt-get install -y -qq docker.io
    systemctl enable docker
    systemctl start docker
fi
log_success "Docker: $(docker --version 2>/dev/null | head -1 || echo 'installed')"

if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null 2>&1; then
    log_error "Docker Compose not found. Installing..."
    apt-get install -y -qq docker-compose
fi
log_success "Docker Compose: available"
echo ""

# Step 2: Find or create Blockscout directory
log_info "Step 2: Locating Blockscout directory..."
if [ -d /opt/blockscout ]; then
    BLOCKSCOUT_DIR="/opt/blockscout"
elif [ -d /root/blockscout ]; then
    BLOCKSCOUT_DIR="/root/blockscout"
else
    BLOCKSCOUT_DIR="/opt/blockscout"
    mkdir -p "$BLOCKSCOUT_DIR"
    log_info "Created directory: $BLOCKSCOUT_DIR"
fi
cd "$BLOCKSCOUT_DIR"
log_success "Blockscout directory: $BLOCKSCOUT_DIR"
echo ""

# Step 3: Create/Update docker-compose.yml with correct settings
log_info "Step 3: Configuring docker-compose.yml..."
cat > docker-compose.yml <<'EOF'
version: '3.8'

services:
  postgres:
    image: postgres:15-alpine
    container_name: blockscout-postgres
    environment:
      POSTGRES_USER: blockscout
      POSTGRES_PASSWORD: blockscout
      POSTGRES_DB: blockscout
    volumes:
      - postgres-data:/var/lib/postgresql/data
    restart: unless-stopped
    networks:
      - blockscout-network
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U blockscout"]
      interval: 10s
      timeout: 5s
      retries: 5

  blockscout:
    image: blockscout/blockscout:latest
    container_name: blockscout
    depends_on:
      postgres:
        condition: service_healthy
    environment:
      - DATABASE_URL=postgresql://blockscout:blockscout@postgres:5432/blockscout
      - ETHEREUM_JSONRPC_HTTP_URL=http://192.168.11.250:8545
      - ETHEREUM_JSONRPC_WS_URL=ws://192.168.11.250:8546
      - ETHEREUM_JSONRPC_TRACE_URL=http://192.168.11.250:8545
      - ETHEREUM_JSONRPC_VARIANT=besu
      - CHAIN_ID=138
      - COIN=ETH
      - BLOCKSCOUT_HOST=192.168.11.140
      - BLOCKSCOUT_PROTOCOL=http
      - SECRET_KEY_BASE=CHANGEME_SECRET_KEY_BASE
      - POOL_SIZE=10
      - ECTO_USE_SSL=false
    ports:
      - "4000:4000"
    volumes:
      - blockscout-data:/app/apps/explorer/priv/static
    restart: unless-stopped
    networks:
      - blockscout-network

volumes:
  postgres-data:
  blockscout-data:

networks:
  blockscout-network:
    driver: bridge
EOF

# Generate and replace secret key
SECRET_KEY=$(openssl rand -hex 64)
sed -i "s|SECRET_KEY_BASE=CHANGEME_SECRET_KEY_BASE|SECRET_KEY_BASE=${SECRET_KEY}|" docker-compose.yml

log_success "docker-compose.yml configured"
echo ""

# Step 4: Stop existing containers
log_info "Step 4: Stopping existing containers..."
docker-compose down 2>/dev/null || docker compose down 2>/dev/null || true
log_success "Existing containers stopped"
echo ""

# Step 5: Start PostgreSQL
log_info "Step 5: Starting PostgreSQL..."
docker-compose up -d postgres || docker compose up -d postgres
log_info "Waiting for PostgreSQL to be ready..."
for i in {1..30}; do
    if docker exec blockscout-postgres pg_isready -U blockscout >/dev/null 2>&1; then
        log_success "PostgreSQL is ready"
        break
    fi
    echo -n "."
    sleep 2
done
echo ""
echo ""

# Step 6: Start Blockscout
log_info "Step 6: Starting Blockscout..."
docker-compose up -d blockscout || docker compose up -d blockscout
log_success "Blockscout started (may take 1-2 minutes to fully initialize)"
echo ""

# Step 7: Configure and start Nginx
log_info "Step 7: Configuring Nginx..."
if ! command -v nginx &> /dev/null; then
    log_info "Installing Nginx..."
    apt-get update -qq
    apt-get install -y -qq nginx
fi

# Configure Nginx
cat > /etc/nginx/sites-available/blockscout <<'EOF'
server {
    listen 80;
    listen [::]:80;
    server_name 192.168.11.140 explorer.d-bis.org;

    client_max_body_size 100M;

    location / {
        proxy_pass http://localhost:4000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        proxy_read_timeout 300s;
        proxy_connect_timeout 75s;
    }

    location /api {
        proxy_pass http://localhost:4000/api;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 300s;
    }

    location /health {
        proxy_pass http://localhost:4000/api/health;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        access_log off;
    }
}
EOF

# Enable site
ln -sf /etc/nginx/sites-available/blockscout /etc/nginx/sites-enabled/blockscout
rm -f /etc/nginx/sites-enabled/default 2>/dev/null || true

# Test and reload Nginx
nginx -t && systemctl reload nginx
systemctl enable nginx
systemctl start nginx

log_success "Nginx configured and running"
echo ""

# Step 8: Check status
log_info "Step 8: Checking service status..."
sleep 5

echo ""
echo "Docker Containers:"
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | head -5

echo ""
echo "Service Status:"
if systemctl is-active --quiet nginx; then
    log_success "Nginx: Running"
else
    log_warn "Nginx: Not running"
fi

if docker ps | grep -q blockscout-postgres; then
    log_success "PostgreSQL: Running"
else
    log_warn "PostgreSQL: Not running"
fi

if docker ps | grep -q "^blockscout "; then
    log_success "Blockscout: Running"
    log_info "Note: Blockscout may take 1-2 minutes to fully start"
else
    log_warn "Blockscout: Not running - check logs: docker logs blockscout"
fi
echo ""

# Step 9: Verify connectivity
log_info "Step 9: Testing connectivity..."
sleep 5

echo ""
echo "Connectivity Tests:"
echo ""

# Test RPC
log_info "Testing RPC endpoint..."
RPC_TEST=$(curl -s -X POST "$RPC_URL" \
    -H 'Content-Type: application/json' \
    -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null || echo "")
if echo "$RPC_TEST" | grep -q '"result"'; then
    BLOCK_HEX=$(echo "$RPC_TEST" | grep -o '"result":"[^"]*"' | cut -d'"' -f4)
    BLOCK_DEC=$(printf "%d" "$BLOCK_HEX" 2>/dev/null || echo "unknown")
    log_success "RPC endpoint accessible (Block: $BLOCK_DEC)"
else
    log_warn "RPC endpoint may not be accessible"
fi

# Test Blockscout API
log_info "Testing Blockscout API..."
for i in {1..6}; do
    API_TEST=$(curl -s http://localhost:4000/api/health 2>/dev/null || echo "")
    if [ -n "$API_TEST" ]; then
        log_success "Blockscout API responding: $API_TEST"
        break
    fi
    if [ $i -lt 6 ]; then
        log_info "Waiting for Blockscout to start... ($i/6)"
        sleep 10
    else
        log_warn "Blockscout API not responding yet (may need more time)"
        log_info "Check logs: docker logs blockscout"
    fi
done

# Test Nginx
log_info "Testing Nginx proxy..."
NGINX_TEST=$(curl -s -o /dev/null -w '%{http_code}' http://localhost/ 2>/dev/null || echo "000")
if [ "$NGINX_TEST" = "200" ] || [ "$NGINX_TEST" = "302" ] || [ "$NGINX_TEST" = "301" ]; then
    log_success "Nginx proxy working (HTTP $NGINX_TEST)"
else
    log_warn "Nginx returned: HTTP $NGINX_TEST"
fi
echo ""

# Final summary
echo "════════════════════════════════════════════════════════"
echo "Configuration Complete!"
echo "════════════════════════════════════════════════════════"
echo ""
echo "Access Points:"
echo "  Internal: http://192.168.11.140"
echo "  External: https://explorer.d-bis.org"
echo "  API: http://192.168.11.140/api"
echo "  Health: http://192.168.11.140/health"
echo ""
echo "Configuration:"
echo "  Chain ID: $CHAIN_ID"
echo "  RPC: $RPC_URL"
echo "  WS: $WS_URL"
echo ""
echo "Useful Commands:"
echo "  View logs: docker-compose logs -f"
echo "  Restart: docker-compose restart"
echo "  Stop: docker-compose down"
echo "  Start: docker-compose up -d"
echo "  Check status: docker ps"
echo ""
log_info "Blockscout may take 1-2 minutes to fully initialize"
log_info "Monitor progress: docker logs -f blockscout"
echo ""

