#!/usr/bin/env bash

# Update Besu configuration on VM
# This script updates Besu configuration and restarts the service

set -e

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

# Configuration
VM_IP="${1:-}"
NODE_TYPE="${2:-validator}"
CONFIG_FILE="${3:-}"


if [ -z "$VM_IP" ]; then
    log_error "Error: VM IP not provided"
    echo "Usage: $0 <vm-ip> <node-type> [config-file]"
    exit 1
fi

log_success "Updating Besu configuration on VM: $VM_IP"

# Copy configuration file
if [ -n "$CONFIG_FILE" ]; then
    log_warn "Copying configuration file..."
    scp "$CONFIG_FILE" besuadmin@$VM_IP:/tmp/besu-config.toml
    ssh besuadmin@$VM_IP "sudo mv /tmp/besu-config.toml /opt/besu/config/besu-config.toml"
    log_success "✓ Configuration file copied"
else
    # Use default configuration
    CONFIG_FILE="$PROJECT_ROOT/config/${NODE_TYPE}s/besu-config.toml"
    if [ -f "$CONFIG_FILE" ]; then
        log_warn "Copying default configuration file..."
        scp "$CONFIG_FILE" besuadmin@$VM_IP:/tmp/besu-config.toml
        ssh besuadmin@$VM_IP "sudo mv /tmp/besu-config.toml /opt/besu/config/besu-config.toml"
        log_success "✓ Configuration file copied"
    else
        log_warn "⚠ Configuration file not found, skipping"
    fi
fi

# Restart Besu service
log_warn "Restarting Besu service..."
ssh besuadmin@$VM_IP "sudo systemctl restart besu.service"
log_success "✓ Besu service restarted"

# Wait for service to be ready
log_warn "Waiting for Besu to be ready..."
sleep 30

# Check service status
if ssh besuadmin@$VM_IP "systemctl is-active --quiet besu.service"; then
    log_success "✓ Besu service is running"
else
    log_error "✗ Besu service failed to start"
    ssh besuadmin@$VM_IP "systemctl status besu.service"
    exit 1
fi

log_success "Configuration update complete!"

