#!/usr/bin/env bash
# Master script to fix all Besu deployment issues
# - Fixes IP addresses (static 192.168.11.X)
# - Validates configuration files
# - Ensures services are running
# - Copies missing configuration files if needed

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# PROJECT_ROOT should be one level up from scripts directory
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Source common functions
if [[ -f "$PROJECT_ROOT/lib/common.sh" ]]; then
    source "$PROJECT_ROOT/lib/common.sh"
else
    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 2>/dev/null || true

log_info "=== Besu Deployment Fix Script ==="
log_info "This script will:"
log_info "1. Fix container IP addresses (192.168.11.X/24)"
log_info "2. Validate Besu configuration files"
log_info "3. Copy missing configuration files if needed"
log_info "4. Fix and start Besu services"
log_info ""

# Check if running on Proxmox host
if ! command_exists pct; then
    error_exit "This script must be run on Proxmox host (pct command not found)"
fi

check_root

# Step 1: Fix IP addresses
log_info ""
log_info "=== Step 1: Fixing Container IP Addresses ==="
if [[ -f "$SCRIPT_DIR/fix-container-ips.sh" ]]; then
    if bash "$SCRIPT_DIR/fix-container-ips.sh"; then
        log_success "IP addresses fixed"
    else
        log_error "Failed to fix IP addresses"
        exit 1
    fi
else
    log_error "fix-container-ips.sh not found"
    exit 1
fi

# Step 2: Check if configuration files need to be copied
log_info ""
log_info "=== Step 2: Checking Configuration Files ==="
SOURCE_PROJECT="${SOURCE_PROJECT:-../smom-dbis-138}"
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" ]] && [[ -f "$SOURCE_PROJECT/config/genesis.json" ]]; then
    log_info "Source project found: $SOURCE_PROJECT"
    
    # Check if we should copy config files
    if [[ -f "$SCRIPT_DIR/copy-besu-config-with-nodes.sh" ]]; then
        log_info "Copying Besu configuration files..."
        if bash "$SCRIPT_DIR/copy-besu-config-with-nodes.sh" "$SOURCE_PROJECT"; then
            log_success "Configuration files copied"
        else
            log_warn "Some configuration files may not have been copied (continuing)"
        fi
    elif [[ -f "$SCRIPT_DIR/copy-besu-config.sh" ]]; then
        log_info "Copying Besu configuration files (using basic script)..."
        if bash "$SCRIPT_DIR/copy-besu-config.sh" "$SOURCE_PROJECT"; then
            log_success "Configuration files copied"
        else
            log_warn "Some configuration files may not have been copied (continuing)"
        fi
    else
        log_warn "Configuration copy script not found, skipping file copy"
    fi
else
    log_warn "Source project not found or genesis.json missing: $SOURCE_PROJECT"
    log_info "Skipping configuration file copy (run copy-besu-config.sh manually if needed)"
fi

# Step 3: Validate configuration
log_info ""
log_info "=== Step 3: Validating Configuration ==="
if [[ -f "$SCRIPT_DIR/validate-besu-config.sh" ]]; then
    if bash "$SCRIPT_DIR/validate-besu-config.sh"; then
        log_success "Configuration validation passed"
    else
        validation_exit=$?
        if [[ $validation_exit -eq 1 ]]; then
            log_error "Configuration validation found errors - please fix before continuing"
            exit 1
        else
            log_warn "Configuration validation found warnings (continuing)"
        fi
    fi
else
    log_warn "validate-besu-config.sh not found, skipping validation"
fi

# Step 4: Fix and start services
log_info ""
log_info "=== Step 4: Fixing and Starting Services ==="
if [[ -f "$SCRIPT_DIR/fix-besu-services.sh" ]]; then
    if bash "$SCRIPT_DIR/fix-besu-services.sh"; then
        log_success "Services fixed and started"
    else
        log_warn "Some services may not have started (check logs)"
    fi
else
    log_error "fix-besu-services.sh not found"
    exit 1
fi

log_info ""
log_success "=== All fixes completed! ==="
log_info ""
log_info "Next steps:"
log_info "1. Verify services are running: pct exec <vmid> -- systemctl status besu-<type>"
log_info "2. Check service logs: pct exec <vmid> -- journalctl -u besu-<type> -f"
log_info "3. Verify network connectivity between nodes"
log_info "4. Update static-nodes.json with actual enodes if needed"

