#!/bin/bash
# Besu Node Setup Script for Backend VMs
# Run this script on each backend VM after SSH access is established

set -euo pipefail

NODE_TYPE="${1:-besu-node}"
NODE_INDEX="${2:-0}"
REGION="${3:-}"

if [ -z "$REGION" ]; then
    echo "Usage: $0 <node-type> <node-index> <region>"
    echo "Example: $0 besu-node 0 eastus"
    exit 1
fi

echo "=========================================="
echo "Besu Node Setup"
echo "=========================================="
echo "Node Type: $NODE_TYPE"
echo "Node Index: $NODE_INDEX"
echo "Region: $REGION"
echo ""

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo "Docker is not installed. Installing Docker..."
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
    sudo apt-get update
    sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
    sudo systemctl enable docker
    sudo systemctl start docker
    sudo usermod -aG docker $USER
    echo "Docker installed. Please log out and log back in for group changes to take effect."
fi

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo "Node.js is not installed. Installing Node.js 22 LTS..."
    if [ ! -d "$HOME/.nvm" ]; then
        curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
        export NVM_DIR="$HOME/.nvm"
        [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
        [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
    else
        export NVM_DIR="$HOME/.nvm"
        [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
    fi
    nvm install 22
    nvm use 22
    nvm alias default 22
    echo "Node.js 22 LTS installed"
fi

# Check if JDK 17 is installed
if ! command -v java &> /dev/null || ! java -version 2>&1 | grep -q "17"; then
    echo "JDK 17 is not installed. Installing OpenJDK 17..."
    sudo apt-get update
    sudo apt-get install -y openjdk-17-jdk
    echo "JDK 17 installed"
fi

# Create Besu directories
echo "Creating Besu directories..."
sudo mkdir -p /opt/besu/{data,config,keys,logs}
sudo chown -R $USER:$USER /opt/besu

# Create Besu configuration
echo "Creating Besu configuration..."
cat > /opt/besu/config/besu-config.toml <<EOF
# Besu Configuration for $NODE_TYPE-$NODE_INDEX
# Region: $REGION

data-path="/opt/besu/data"
genesis-file="/opt/besu/config/genesis.json"

# Network
network-id=138
p2p-port=30303
rpc-http-enabled=true
rpc-http-host="0.0.0.0"
rpc-http-port=8545
rpc-http-cors-origins=["*"]
rpc-http-api=["ETH","NET","WEB3","ADMIN","DEBUG","TRACE","TXPOOL","PERSONAL","EOA","PERM","PLUGINS","QBFT","IBFT","CLIQUE","MINER"]

# WebSocket
rpc-ws-enabled=true
rpc-ws-host="0.0.0.0"
rpc-ws-port=8546
rpc-ws-api=["ETH","NET","WEB3","ADMIN","DEBUG","TRACE","TXPOOL","PERSONAL","EOA","PERM","PLUGINS","QBFT","IBFT","CLIQUE","MINER"]

# Metrics
metrics-enabled=true
metrics-host="0.0.0.0"
metrics-port=9545
metrics-category-enabled=["blockchain","jvm","process","peers","rpc"]

# Logging
logging="INFO"
log-destination="FILE"
log-file="/opt/besu/logs/besu.log"
EOF

# Create docker-compose.yml
echo "Creating docker-compose.yml..."
cat > /opt/besu/docker-compose.yml <<EOF
version: '3.8'

services:
  besu:
    image: hyperledger/besu:23.10.0
    container_name: besu-${NODE_TYPE}-${NODE_INDEX}
    restart: unless-stopped
    user: "$USER"
    volumes:
      - /opt/besu/data:/data
      - /opt/besu/config:/config
      - /opt/besu/keys:/keys:ro
      - /opt/besu/logs:/logs
    ports:
      - "9545:9545"  # Metrics
      - "30303:30303"  # P2P TCP
      - "30303:30303/udp"  # P2P UDP
      - "8545:8545"  # RPC HTTP
      - "8546:8546"  # WebSocket
    command:
      - /opt/besu/bin/besu
      - --config-file=/config/besu-config.toml
    environment:
      - BESU_OPTS=-Xmx4g -Xms4g
    networks:
      - besu-network
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
    healthcheck:
      test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:9545/metrics"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 120s

networks:
  besu-network:
    driver: bridge
EOF

# Create systemd service
echo "Creating systemd service..."
sudo tee /etc/systemd/system/besu.service > /dev/null <<EOF
[Unit]
Description=Besu Node Service
After=docker.service
Requires=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/opt/besu
ExecStart=/usr/bin/docker compose up -d
ExecStop=/usr/bin/docker compose down
Restart=on-failure
RestartSec=10
User=$USER
Group=$USER

[Install]
WantedBy=multi-user.target
EOF

# Download genesis file (placeholder - user needs to provide actual genesis file)
echo "NOTE: You need to provide a genesis.json file at /opt/besu/config/genesis.json"
echo "      For now, creating a placeholder..."

cat > /opt/besu/config/genesis.json <<EOF
{
  "config": {
    "chainId": 138,
    "homesteadBlock": 0,
    "eip150Block": 0,
    "eip155Block": 0,
    "eip158Block": 0,
    "byzantiumBlock": 0,
    "constantinopleBlock": 0,
    "petersburgBlock": 0,
    "istanbulBlock": 0,
    "berlinBlock": 0,
    "londonBlock": 0,
    "arrowGlacierBlock": 0,
    "grayGlacierBlock": 0,
    "mergeNetSplitBlock": 0,
    "shanghaiTime": 0,
    "cancunTime": 0
  },
  "difficulty": "0x1",
  "gasLimit": "0x1C9C380",
  "alloc": {}
}
EOF

echo "Genesis file placeholder created. Replace with actual genesis.json for your network."

# Enable and start service
echo "Enabling Besu service..."
sudo systemctl daemon-reload
sudo systemctl enable besu.service

echo ""
echo "=========================================="
echo "Besu Node Setup Complete!"
echo "=========================================="
echo "Configuration: /opt/besu/config/besu-config.toml"
echo "Data directory: /opt/besu/data"
echo "Logs: /opt/besu/logs"
echo ""
echo "Next steps:"
echo "1. Replace /opt/besu/config/genesis.json with your actual genesis file"
echo "2. If this is a validator, add validator keys to /opt/besu/keys/"
echo "3. Start the service: sudo systemctl start besu.service"
echo "4. Check status: sudo systemctl status besu.service"
echo "5. View logs: sudo journalctl -u besu.service -f"
echo "6. Check Docker logs: docker logs besu-${NODE_TYPE}-${NODE_INDEX}"
echo ""

