#!/usr/bin/env bash
# Setup Docker and Besu containers in temporary VM
# This script should be run inside the temporary VM

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

BESU_DATA="/opt/besu"
SOURCE_PROJECT="${1:-/opt/smom-dbis-138}"

log_info() { echo "[INFO] $1"; }
log_success() { echo "[✓] $1"; }
log_warn() { echo "[WARNING] $1"; }
log_error() { echo "[ERROR] $1"; exit 1; }

log_info "Setting up Docker and Besu environment..."

# Update system
log_info "Updating system packages..."
export DEBIAN_FRONTEND=noninteractive
export LC_ALL=C
export LANG=C

apt-get update -qq
apt-get upgrade -y -qq

# Install prerequisites
log_info "Installing prerequisites..."
apt-get install -y -qq \
    ca-certificates \
    curl \
    gnupg \
    lsb-release \
    wget \
    jq \
    git \
    vim \
    net-tools \
    iproute2

log_success "Prerequisites installed"

# Install Docker
log_info "Installing Docker..."
if command -v docker >/dev/null 2>&1; then
    log_info "Docker already installed, skipping..."
else
    install -m 0755 -d /etc/apt/keyrings
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
    chmod a+r /etc/apt/keyrings/docker.gpg

    echo \
      "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
      $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null

    apt-get update -qq
    apt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

    systemctl enable docker
    systemctl start docker

    log_success "Docker installed"
fi

# Verify Docker is running
if ! systemctl is-active --quiet docker; then
    log_error "Docker service is not running"
    exit 1
fi

# Create directories
log_info "Creating Besu directories..."
mkdir -p "$BESU_DATA"/{validators,sentries,rpc}/{data,config,keys,logs}
mkdir -p "$BESU_DATA"/shared/{genesis,permissions}

# Create subdirectories for each node
for i in {1..5}; do
    mkdir -p "$BESU_DATA/validators/validator-$i"/{data,config,keys,logs}
done

for i in {1..4}; do
    mkdir -p "$BESU_DATA/sentries/sentry-$i"/{data,config,keys,logs}
done

for i in {1..3}; do
    mkdir -p "$BESU_DATA/rpc/rpc-$i"/{data,config,keys,logs}
done

log_success "Directories created"

# Copy configuration files from source project
if [[ -d "$SOURCE_PROJECT" ]]; then
    log_info "Copying configuration files from $SOURCE_PROJECT..."
    
    # Copy genesis.json
    if [[ -f "$SOURCE_PROJECT/config/genesis.json" ]]; then
        cp "$SOURCE_PROJECT/config/genesis.json" "$BESU_DATA/shared/genesis/"
        log_success "Copied genesis.json"
    else
        log_warn "genesis.json not found at $SOURCE_PROJECT/config/genesis.json"
    fi
    
    # Copy static-nodes.json
    if [[ -f "$SOURCE_PROJECT/config/static-nodes.json" ]]; then
        cp "$SOURCE_PROJECT/config/static-nodes.json" "$BESU_DATA/shared/genesis/"
        log_success "Copied static-nodes.json"
    else
        log_warn "static-nodes.json not found"
    fi
    
    # Copy permissions files
    if [[ -f "$SOURCE_PROJECT/config/permissions-nodes.toml" ]]; then
        cp "$SOURCE_PROJECT/config/permissions-nodes.toml" "$BESU_DATA/shared/permissions/"
        log_success "Copied permissions-nodes.toml"
    else
        log_warn "permissions-nodes.toml not found"
    fi
    
    if [[ -f "$SOURCE_PROJECT/config/permissions-accounts.toml" ]]; then
        cp "$SOURCE_PROJECT/config/permissions-accounts.toml" "$BESU_DATA/shared/permissions/" 2>/dev/null || true
    fi
    
    # Copy validator keys
    if [[ -d "$SOURCE_PROJECT/keys/validators" ]]; then
        for i in {1..5}; do
            if [[ -d "$SOURCE_PROJECT/keys/validators/validator-$i" ]]; then
                cp -r "$SOURCE_PROJECT/keys/validators/validator-$i"/* "$BESU_DATA/validators/validator-$i/keys/" 2>/dev/null || true
                log_info "Copied keys for validator-$i"
            fi
        done
        log_success "Copied validator keys"
    else
        log_warn "Validator keys directory not found at $SOURCE_PROJECT/keys/validators"
    fi
    
    # Copy sentry keys if they exist
    if [[ -d "$SOURCE_PROJECT/keys/sentries" ]]; then
        for i in {1..4}; do
            if [[ -d "$SOURCE_PROJECT/keys/sentries/sentry-$i" ]]; then
                cp -r "$SOURCE_PROJECT/keys/sentries/sentry-$i"/* "$BESU_DATA/sentries/sentry-$i/keys/" 2>/dev/null || true
            fi
        done
        log_success "Copied sentry keys"
    fi
    
    # Copy RPC keys if they exist
    if [[ -d "$SOURCE_PROJECT/keys/rpc" ]]; then
        for i in {1..3}; do
            if [[ -d "$SOURCE_PROJECT/keys/rpc/rpc-$i" ]]; then
                cp -r "$SOURCE_PROJECT/keys/rpc/rpc-$i"/* "$BESU_DATA/rpc/rpc-$i/keys/" 2>/dev/null || true
            fi
        done
        log_success "Copied RPC keys"
    fi
else
    log_warn "Source project not found at $SOURCE_PROJECT"
    log_warn "You'll need to copy configuration files manually"
fi

# Copy docker-compose file if it exists
if [[ -f "$PROJECT_ROOT/templates/docker-compose-besu-temp.yml" ]]; then
    cp "$PROJECT_ROOT/templates/docker-compose-besu-temp.yml" "$BESU_DATA/docker-compose.yml"
    log_success "Copied docker-compose.yml"
fi

# Copy config templates
if [[ -d "$PROJECT_ROOT/templates/besu-configs" ]]; then
    log_info "Copying Besu configuration templates..."
    cp -r "$PROJECT_ROOT/templates/besu-configs"/* "$BESU_DATA/" 2>/dev/null || true
    log_success "Configuration templates available"
fi

log_success "Docker setup complete!"
log_info ""
log_info "Next steps:"
log_info "1. Review and customize config files in $BESU_DATA"
log_info "2. Ensure all keys are in place"
log_info "3. Start containers: cd $BESU_DATA && docker compose up -d"
log_info "4. Check logs: docker compose logs -f"

