#!/bin/bash
# Complete Blockscout setup and configuration
# Run this inside the Blockscout container (VMID 5000)

set -euo pipefail

# 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 "Complete Blockscout Setup and Configuration"
echo "════════════════════════════════════════════════════════"
echo ""

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

log_info "Configuration:"
echo "  Chain ID: $CHAIN_ID"
echo "  RPC URL: $RPC_URL"
echo "  WS URL: $WS_URL"
echo "  Host: $BLOCKSCOUT_HOST"
echo ""

# Check if running inside container
if [ ! -f /.dockerenv ] && [ ! -d /sys/fs/cgroup/systemd ]; then
    log_warn "This script should be run inside the Blockscout container"
    log_info "SSH to container first: ssh root@192.168.11.140"
    exit 1
fi

# Step 1: Check Docker and Docker Compose
log_info "Step 1: Checking Docker..."
if command -v docker &> /dev/null; then
    log_success "Docker installed: $(docker --version)"
else
    log_error "Docker not found. Installing..."
    apt-get update
    apt-get install -y docker.io docker-compose
    systemctl enable docker
    systemctl start docker
    log_success "Docker installed"
fi

if command -v docker-compose &> /dev/null || docker compose version &> /dev/null; then
    log_success "Docker Compose available"
else
    log_error "Docker Compose not found. Installing..."
    apt-get install -y docker-compose
    log_success "Docker Compose installed"
fi
echo ""

# Step 2: Check PostgreSQL
log_info "Step 2: Checking PostgreSQL..."
if docker ps -a | grep -q postgres; then
    log_success "PostgreSQL container exists"
    if docker ps | grep -q postgres; then
        log_success "PostgreSQL is running"
    else
        log_info "Starting PostgreSQL..."
        cd /root/blockscout 2>/dev/null || cd /opt/blockscout 2>/dev/null || cd ~
        if [ -f docker-compose.yml ]; then
            docker-compose up -d postgres || docker compose up -d postgres
            sleep 5
            log_success "PostgreSQL started"
        fi
    fi
else
    log_warn "PostgreSQL container not found"
fi
echo ""

# Step 3: Check Blockscout directory
log_info "Step 3: Checking Blockscout installation..."
BLOCKSCOUT_DIR=""
if [ -d /root/blockscout ]; then
    BLOCKSCOUT_DIR="/root/blockscout"
elif [ -d /opt/blockscout ]; then
    BLOCKSCOUT_DIR="/opt/blockscout"
else
    log_info "Creating Blockscout directory..."
    BLOCKSCOUT_DIR="/root/blockscout"
    mkdir -p "$BLOCKSCOUT_DIR"
    log_success "Created directory: $BLOCKSCOUT_DIR"
fi
cd "$BLOCKSCOUT_DIR"
log_success "Blockscout directory: $BLOCKSCOUT_DIR"
echo ""

# Step 4: Create/Update docker-compose.yml
log_info "Step 4: 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: ${DB_PASSWORD}
      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:${DB_PASSWORD}@postgres:5432/blockscout
      - ETHEREUM_JSONRPC_HTTP_URL=${RPC_URL}
      - ETHEREUM_JSONRPC_WS_URL=${WS_URL}
      - ETHEREUM_JSONRPC_TRACE_URL=${RPC_URL}
      - ETHEREUM_JSONRPC_VARIANT=besu
      - CHAIN_ID=${CHAIN_ID}
      - COIN=ETH
      - BLOCKSCOUT_HOST=${BLOCKSCOUT_HOST}
      - BLOCKSCOUT_PROTOCOL=http
      - SECRET_KEY_BASE=\$(openssl rand -hex 64)
      - POOL_SIZE=10
      - ECTO_USE_SSL=false
    ports:
      - "4000:4000"
    volumes:
      - blockscout-data:/app/apps/explorer/priv/static
    restart: unless-stopped
    networks:
      - blockscout-network
    healthcheck:
      test: ["CMD-SHELL", "curl -f http://localhost:4000/api/health || exit 1"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 60s

volumes:
  postgres-data:
  blockscout-data:

networks:
  blockscout-network:
    driver: bridge
EOF

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

# Step 5: Generate secret key if needed
log_info "Step 5: Generating secret key..."
SECRET_KEY=$(openssl rand -hex 64)
if grep -q "SECRET_KEY_BASE" docker-compose.yml; then
    sed -i "s|SECRET_KEY_BASE=.*|SECRET_KEY_BASE=${SECRET_KEY}|" docker-compose.yml
    log_success "Secret key generated"
fi
echo ""

# Step 6: Check Nginx
log_info "Step 6: Checking Nginx..."
if command -v nginx &> /dev/null; then
    log_success "Nginx installed"
    if systemctl is-active --quiet nginx; then
        log_success "Nginx is running"
    else
        log_info "Starting Nginx..."
        systemctl start nginx
        systemctl enable nginx
        log_success "Nginx started"
    fi
    
    # Configure Nginx for Blockscout
    log_info "Configuring Nginx..."
    cat > /etc/nginx/sites-available/blockscout <<EOF
server {
    listen 80;
    listen [::]:80;
    server_name ${BLOCKSCOUT_HOST} explorer.d-bis.org;

    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;
    }
}
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
    log_success "Nginx configured for Blockscout"
else
    log_warn "Nginx not installed. Installing..."
    apt-get update
    apt-get install -y nginx
    systemctl enable nginx
    systemctl start nginx
    log_success "Nginx installed"
fi
echo ""

# Step 7: Start Blockscout services
log_info "Step 7: Starting Blockscout services..."
cd "$BLOCKSCOUT_DIR"

# Stop existing containers
docker-compose down 2>/dev/null || docker compose down 2>/dev/null || true

# Start services
log_info "Starting PostgreSQL..."
docker-compose up -d postgres || docker compose up -d postgres

log_info "Waiting for PostgreSQL to be ready..."
sleep 10

# Check PostgreSQL health
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
    log_info "Waiting for PostgreSQL... ($i/30)"
    sleep 2
done

log_info "Starting Blockscout..."
docker-compose up -d blockscout || docker compose up -d blockscout

log_success "Blockscout services started"
echo ""

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

echo ""
echo "Container Status:"
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

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"
else
    log_warn "Blockscout: Not running"
fi
echo ""

# Step 9: Verify connectivity
log_info "Step 9: Verifying connectivity..."
sleep 10

echo ""
echo "Connectivity Tests:"
echo "  RPC: curl -s -X POST $RPC_URL -H 'Content-Type: application/json' -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}'"
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
    log_success "RPC endpoint accessible"
else
    log_warn "RPC endpoint may not be accessible"
fi

echo ""
echo "  Blockscout API: curl -s http://localhost:4000/api/health"
API_TEST=$(curl -s http://localhost:4000/api/health 2>/dev/null || echo "")
if echo "$API_TEST" | grep -q "healthy\|ok"; then
    log_success "Blockscout API is responding"
elif [ -n "$API_TEST" ]; then
    log_warn "Blockscout API returned: $API_TEST"
else
    log_warn "Blockscout API not responding yet (may need more time to start)"
fi

echo ""
echo "  Nginx: curl -s http://localhost/"
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 is working (HTTP $NGINX_TEST)"
else
    log_warn "Nginx returned: HTTP $NGINX_TEST"
fi
echo ""

# Final summary
echo "════════════════════════════════════════════════════════"
echo "Setup Complete!"
echo "════════════════════════════════════════════════════════"
echo ""
echo "Configuration:"
echo "  Chain ID: $CHAIN_ID"
echo "  RPC URL: $RPC_URL"
echo "  WS URL: $WS_URL"
echo "  Host: $BLOCKSCOUT_HOST"
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 ""
echo "Service Management:"
echo "  View logs: docker-compose logs -f"
echo "  Restart: docker-compose restart"
echo "  Stop: docker-compose down"
echo "  Start: docker-compose up -d"
echo ""
echo "Note: Blockscout may take 1-2 minutes to fully initialize"
echo "Monitor logs: docker-compose logs -f blockscout"
echo ""

