#!/bin/bash
# Blockscout Configuration - Run these commands directly in the container
# Copy and paste this entire script into your SSH session to container

set -e

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

echo "════════════════════════════════════════════════════════"
echo "Configuring Blockscout with correct settings..."
echo "════════════════════════════════════════════════════════"
echo ""

# Step 1: Ensure Docker is running
echo "Step 1: Checking Docker..."
systemctl start docker 2>/dev/null || true
systemctl enable docker 2>/dev/null || true
echo "✓ Docker checked"
echo ""

# Step 2: Navigate to Blockscout directory
echo "Step 2: Setting up Blockscout directory..."
if [ -d /opt/blockscout ]; then
    cd /opt/blockscout
elif [ -d /root/blockscout ]; then
    cd /root/blockscout
else
    mkdir -p /opt/blockscout
    cd /opt/blockscout
fi
echo "✓ Working directory: $(pwd)"
echo ""

# Step 3: Create docker-compose.yml
echo "Step 3: Creating 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=PLACEHOLDER_SECRET_KEY
      - 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 secret key
SECRET_KEY=$(openssl rand -hex 64)
sed -i "s|SECRET_KEY_BASE=PLACEHOLDER_SECRET_KEY|SECRET_KEY_BASE=${SECRET_KEY}|" docker-compose.yml
echo "✓ docker-compose.yml created"
echo ""

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

# Step 5: Start PostgreSQL
echo "Step 5: Starting PostgreSQL..."
docker-compose up -d postgres || docker compose up -d postgres
echo "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
        echo "✓ PostgreSQL is ready"
        break
    fi
    echo -n "."
    sleep 2
done
echo ""
echo ""

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

# Step 7: Configure Nginx
echo "Step 7: Configuring Nginx..."
apt-get update -qq
apt-get install -y -qq nginx >/dev/null 2>&1

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

ln -sf /etc/nginx/sites-available/blockscout /etc/nginx/sites-enabled/blockscout
rm -f /etc/nginx/sites-enabled/default
nginx -t >/dev/null 2>&1 && systemctl reload nginx
systemctl enable nginx >/dev/null 2>&1
systemctl start nginx >/dev/null 2>&1
echo "✓ Nginx configured and started"
echo ""

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

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

# Step 9: Test connectivity
echo "Step 9: Testing connectivity..."
sleep 5

echo "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
    echo "✓ RPC endpoint accessible"
else
    echo "⚠ RPC endpoint may not be accessible"
fi

echo ""
echo "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
        echo "✓ Blockscout API responding: $API_TEST"
        break
    fi
    if [ $i -lt 6 ]; then
        echo "Waiting for Blockscout... ($i/6)"
        sleep 10
    else
        echo "⚠ Blockscout API not responding yet (may need more time)"
    fi
done

echo ""
echo "Testing Nginx..."
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
    echo "✓ Nginx proxy working (HTTP $NGINX_TEST)"
else
    echo "⚠ 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 ""
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 "  Check status: docker ps"
echo "  Restart: docker-compose restart"
echo ""
echo "Note: Blockscout may take 1-2 minutes to fully initialize"
echo "Monitor: docker logs -f blockscout"
echo ""

