#!/usr/bin/env bash
# Upgrade individual Besu node

set -euo pipefail

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

source "$PROJECT_ROOT/lib/common.sh"

if [[ $# -lt 1 ]]; then
    log_error "Usage: $0 <vmid|hostname> [version]"
    exit 1
fi

NODE_ID="$1"
BESU_VERSION="${2:-23.10.0}"

load_config

# Get VMID from hostname if needed
if [[ ! "$NODE_ID" =~ ^[0-9]+$ ]]; then
    # Try to find VMID from hostname
    VMID=$(pct list | grep "$NODE_ID" | awk '{print $1}' | head -1)
    if [[ -z "$VMID" ]]; then
        error_exit "Container not found: $NODE_ID"
    fi
else
    VMID="$NODE_ID"
fi

log_info "Upgrading node $VMID to Besu version $BESU_VERSION"

# Check if container exists
if ! pct list | grep -q "^\s*$VMID\s"; then
    error_exit "Container $VMID not found"
fi

# Get container status
CONTAINER_STATUS=$(pct status "$VMID" | awk '{print $2}')

# Backup before upgrade
log_info "Creating backup before upgrade..."
BACKUP_DIR=$(create_backup_dir)
pct snapshot "$VMID" "pre-upgrade-$(date +%Y%m%d-%H%M%S)"
log_success "Backup created"

# Stop service if running
if [[ "$CONTAINER_STATUS" == "running" ]]; then
    log_info "Stopping Besu service..."
    pct exec "$VMID" -- systemctl stop besu-validator.service 2>/dev/null || true
    pct exec "$VMID" -- systemctl stop besu-sentry.service 2>/dev/null || true
    pct exec "$VMID" -- systemctl stop besu-rpc.service 2>/dev/null || true
fi

# Upgrade Besu
log_info "Downloading and installing Besu $BESU_VERSION..."
BESU_DOWNLOAD_URL="https://hyperledger.jfrog.io/hyperledger/besu-binaries/besu/${BESU_VERSION}/besu-${BESU_VERSION}.tar.gz"
BESU_TAR="/tmp/besu-${BESU_VERSION}.tar.gz"

pct exec "$VMID" -- bash -c "
    cd /tmp && \
    wget -q '$BESU_DOWNLOAD_URL' -O '$BESU_TAR' && \
    tar -xzf '$BESU_TAR' -C /opt/besu --strip-components=1 && \
    chmod +x /opt/besu/bin/besu && \
    chown -R besu:besu /opt/besu && \
    rm -f '$BESU_TAR'
" || error_exit "Besu upgrade failed"

log_success "Besu upgraded to version $BESU_VERSION"

# Start service
if [[ "$CONTAINER_STATUS" == "running" ]]; then
    log_info "Starting Besu service..."
    pct exec "$VMID" -- systemctl start besu-validator.service 2>/dev/null || \
    pct exec "$VMID" -- systemctl start besu-sentry.service 2>/dev/null || \
    pct exec "$VMID" -- systemctl start besu-rpc.service 2>/dev/null || \
    log_warn "Could not determine which service to start"
fi

# Verify upgrade
log_info "Verifying upgrade..."
sleep 5
if pct exec "$VMID" -- /opt/besu/bin/besu --version | grep -q "$BESU_VERSION"; then
    log_success "Upgrade verified successfully"
else
    log_warn "Version verification failed, but upgrade may have succeeded"
fi

log_success "Node $VMID upgraded successfully"

