#!/usr/bin/env bash
# Copy Besu configuration files from smom-dbis-138 project to containers
# This script copies genesis.json, config files, and validator keys

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# PROJECT_ROOT is smom-dbis-138-proxmox directory
if [[ "$SCRIPT_DIR" == *"/scripts"* ]]; then
    PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
else
    PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
fi

# Source common functions if available
if [[ -f "$PROJECT_ROOT/lib/common.sh" ]]; then
    source "$PROJECT_ROOT/lib/common.sh"
else
    # Fallback functions if common.sh not available
    log_info() { echo "[INFO] $1"; }
    log_success() { echo "[✓] $1"; }
    log_warn() { echo "[WARNING] $1"; }
    log_error() { echo "[ERROR] $1"; exit 1; }
    error_exit() { echo "[ERROR] $1"; exit 1; }
fi

load_config

# Source project directory (relative to deployment directory)
SOURCE_PROJECT="${1:-../smom-dbis-138}"
# Convert to absolute path if relative
if [[ "$SOURCE_PROJECT" != /* ]]; then
    SOURCE_PROJECT="$(cd "$PROJECT_ROOT" && cd "$SOURCE_PROJECT" && pwd 2>/dev/null || echo "$PROJECT_ROOT/$SOURCE_PROJECT")"
fi

if [[ ! -d "$SOURCE_PROJECT" ]]; then
    error_exit "Source project directory not found: $SOURCE_PROJECT"
fi

log_info "Copying Besu configuration files from: $SOURCE_PROJECT"
log_info "Target containers: Validators (1000-1004), Sentries (1500-1503), RPC (2500-2502)"

# Define container arrays (new ranges)
VALIDATORS=(1000 1001 1002 1003 1004)
SENTRIES=(1500 1501 1502 1503)
RPCS=(2500 2501 2502)
ALL_BESU=("${VALIDATORS[@]}" "${SENTRIES[@]}" "${RPCS[@]}")

# Function to copy file to container
copy_to_container() {
    local vmid="$1"
    local source_file="$2"
    local dest_file="$3"
    
    if [[ ! -f "$source_file" ]]; then
        log_warn "Source file not found: $source_file (skipping container $vmid)"
        return 1
    fi
    
    if ! pct status "$vmid" 2>/dev/null | grep -q running; then
        log_warn "Container $vmid is not running (skipping)"
        return 1
    fi
    
    log_info "Copying to container $vmid: $(basename "$source_file") -> $dest_file"
    pct push "$vmid" "$source_file" "$dest_file" || {
        log_error "Failed to copy $source_file to container $vmid"
        return 1
    }
    
    # Set ownership to besu user
    pct exec "$vmid" -- chown besu:besu "$dest_file" 2>/dev/null || true
    
    return 0
}

# Copy genesis.json to all Besu containers
log_info ""
log_info "=== Copying genesis.json ==="
GENESIS_FILE="$SOURCE_PROJECT/config/genesis.json"
if [[ -f "$GENESIS_FILE" ]]; then
    for vmid in "${ALL_BESU[@]}"; do
        copy_to_container "$vmid" "$GENESIS_FILE" "/etc/besu/genesis.json"
    done
    log_success "genesis.json copied to all containers"
else
    log_warn "genesis.json not found at: $GENESIS_FILE"
fi

# Copy config-validator.toml (create from template if needed)
log_info ""
log_info "=== Copying/creating config-validator.toml ==="
CONFIG_FILE="$SOURCE_PROJECT/config/config-validator.toml"
if [[ -f "$CONFIG_FILE" ]]; then
    for vmid in "${VALIDATORS[@]}"; do
        copy_to_container "$vmid" "$CONFIG_FILE" "/etc/besu/config-validator.toml"
    done
    log_success "config-validator.toml copied to validators"
else
    log_warn "config-validator.toml not found, creating from template..."
    # Copy template and customize for each validator
    for vmid in "${VALIDATORS[@]}"; do
        if pct status "$vmid" 2>/dev/null | grep -q running; then
            pct exec "$vmid" -- cp /etc/besu/config-validator.toml.template /etc/besu/config-validator.toml 2>/dev/null || true
            pct exec "$vmid" -- chown besu:besu /etc/besu/config-validator.toml 2>/dev/null || true
        fi
    done
fi

# Copy config-sentry.toml for sentries
log_info ""
log_info "=== Copying/creating config-sentry.toml ==="
# Try config-sentry.toml first, then config-member.toml as fallback (for backwards compatibility)
SENTRY_CONFIG=""
if [[ -f "$SOURCE_PROJECT/config/config-sentry.toml" ]]; then
    SENTRY_CONFIG="$SOURCE_PROJECT/config/config-sentry.toml"
elif [[ -f "$SOURCE_PROJECT/config/config-member.toml" ]]; then
    SENTRY_CONFIG="$SOURCE_PROJECT/config/config-member.toml"
    log_info "Using config-member.toml as fallback (consider renaming to config-sentry.toml)"
fi

if [[ -n "${SENTRY_CONFIG:-}" ]] && [[ -f "$SENTRY_CONFIG" ]]; then
    for vmid in "${SENTRIES[@]}"; do
        copy_to_container "$vmid" "$SENTRY_CONFIG" "/etc/besu/config-sentry.toml"
    done
    log_success "config-sentry.toml copied to sentries"
else
    log_warn "config-sentry.toml not found, using validator template..."
    for vmid in "${SENTRIES[@]}"; do
        if pct status "$vmid" 2>/dev/null | grep -q running; then
            pct exec "$vmid" -- cp /etc/besu/config-validator.toml.template /etc/besu/config-sentry.toml 2>/dev/null || true
            pct exec "$vmid" -- chown besu:besu /etc/besu/config-sentry.toml 2>/dev/null || true
        fi
    done
fi

# Copy RPC config files - Each VMID maps to a specific RPC type
log_info ""
log_info "=== Copying RPC node config files (type-specific) ==="

# RPC Node Type Mapping
declare -A RPC_VMID_TO_TYPE
RPC_VMID_TO_TYPE[2500]="core"      # Core RPC
RPC_VMID_TO_TYPE[2501]="perm"      # Permissioned RPC
RPC_VMID_TO_TYPE[2502]="public"    # Public RPC

declare -A RPC_TYPE_TO_CONFIG
RPC_TYPE_TO_CONFIG["core"]="config-rpc-core.toml"
RPC_TYPE_TO_CONFIG["perm"]="config-rpc-perm.toml"
RPC_TYPE_TO_CONFIG["public"]="config-rpc-public.toml"

for vmid in "${RPCS[@]}"; do
    rpc_type="${RPC_VMID_TO_TYPE[$vmid]}"
    config_filename="${RPC_TYPE_TO_CONFIG[$rpc_type]}"
    
    if [[ -z "$rpc_type" ]] || [[ -z "$config_filename" ]]; then
        log_warn "Unknown RPC type mapping for VMID $vmid, skipping"
        continue
    fi
    
    # Try to find the specific config file
    config_file="$SOURCE_PROJECT/config/$config_filename"
    
    if [[ -f "$config_file" ]]; then
        copy_to_container "$vmid" "$config_file" "/etc/besu/$config_filename"
        log_info "Copied $config_filename to RPC node $vmid (type: $rpc_type)"
        
        # Update systemd service file to use the correct config file
        pct exec "$vmid" -- sed -i "s|--config-file=\$BESU_CONFIG/config-rpc-public.toml|--config-file=\$BESU_CONFIG/$config_filename|g" /etc/systemd/system/besu-rpc.service 2>/dev/null || {
            log_warn "Failed to update systemd service file for $vmid (may need manual update)"
        }
        pct exec "$vmid" -- systemctl daemon-reload 2>/dev/null || true
    else
        log_warn "Config file not found for RPC $vmid (type: $rpc_type, expected: $config_filename)"
        # Fallback: try config-rpc-public.toml as last resort
        if [[ "$rpc_type" != "public" ]] && [[ -f "$SOURCE_PROJECT/config/config-rpc-public.toml" ]]; then
            log_warn "Using config-rpc-public.toml as fallback for $vmid (type: $rpc_type)"
            copy_to_container "$vmid" "$SOURCE_PROJECT/config/config-rpc-public.toml" "/etc/besu/$config_filename"
        fi
    fi
done
log_success "RPC config files copied (type-specific)"

# Copy permissions files
log_info ""
log_info "=== Copying permissions files ==="
for perm_file in "permissions-nodes.toml" "permissions-accounts.toml"; do
    PERM_FILE="$SOURCE_PROJECT/config/$perm_file"
    if [[ -f "$PERM_FILE" ]]; then
        for vmid in "${ALL_BESU[@]}"; do
            copy_to_container "$vmid" "$PERM_FILE" "/etc/besu/$perm_file"
        done
        log_success "$perm_file copied to all containers"
    else
        log_warn "$perm_file not found at: $PERM_FILE"
    fi
done

# Copy validator keys (only to validators)
log_info ""
log_info "=== Copying validator keys ==="
KEYS_DIR="$SOURCE_PROJECT/keys/validators"
if [[ -d "$KEYS_DIR" ]]; then
    for vmid in "${VALIDATORS[@]}"; do
        if pct status "$vmid" 2>/dev/null | grep -q running; then
            log_info "Copying validator keys to container $vmid..."
            # Create keys directory
            pct exec "$vmid" -- mkdir -p /keys/validators 2>/dev/null || true
            # Copy keys (use rsync-like approach with tar)
            for key_dir in "$KEYS_DIR"/validator-*; do
                if [[ -d "$key_dir" ]]; then
                    validator_name=$(basename "$key_dir")
                    log_info "  Copying $validator_name keys..."
                    # Create temp tar, push, extract
                    tar -C "$KEYS_DIR" -czf /tmp/keys-$$.tar.gz "$validator_name" 2>/dev/null
                    pct push "$vmid" /tmp/keys-$$.tar.gz /tmp/keys-$$.tar.gz
                    pct exec "$vmid" -- mkdir -p "/keys/validators/$validator_name" 2>/dev/null || true
                    pct exec "$vmid" -- tar -xzf /tmp/keys-$$.tar.gz -C /keys/validators/ 2>/dev/null || true
                    pct exec "$vmid" -- rm -f /tmp/keys-$$.tar.gz 2>/dev/null || true
                    rm -f /tmp/keys-$$.tar.gz 2>/dev/null || true
                fi
            done
            # Set ownership
            pct exec "$vmid" -- chown -R besu:besu /keys 2>/dev/null || true
        fi
    done
    log_success "Validator keys copied"
else
    log_warn "Validator keys directory not found at: $KEYS_DIR"
fi

# Create static-nodes.json (will be updated later with actual enodes)
log_info ""
log_info "=== Creating static-nodes.json placeholder ==="
STATIC_NODES_TEMP="/tmp/static-nodes.json"
cat > "$STATIC_NODES_TEMP" <<'EOF'
[]
EOF

for vmid in "${ALL_BESU[@]}"; do
    if pct status "$vmid" 2>/dev/null | grep -q running; then
        copy_to_container "$vmid" "$STATIC_NODES_TEMP" "/etc/besu/static-nodes.json"
    fi
done
rm -f "$STATIC_NODES_TEMP"

log_success "Configuration files copied!"
log_info ""
log_info "Next steps:"
log_info "1. Update static-nodes.json with actual enodes: ./scripts/network/update-static-nodes.sh"
log_info "2. Start Besu services in containers"
log_info "3. Verify services are running"

