#!/usr/bin/env bash
# Restart Besu node (clears mempool)
# Usage: ./restart-besu-node.sh <vmid> [service-type]
#
# This script restarts a Besu node, which will clear the mempool.
# Useful for resolving stuck transactions or mempool-related issues.
#
# Examples:
#   ./restart-besu-node.sh 1000              # Auto-detect service type
#   ./restart-besu-node.sh 2500 validator    # Specify service type
#   ./restart-besu-node.sh validator-1       # Use hostname

set -euo pipefail

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

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

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Check if running on Proxmox host
if ! command -v pct &>/dev/null; then
    log_error "This script must be run on Proxmox host (pct command not found)"
    exit 1
fi

# Parse arguments
if [[ $# -lt 1 ]]; then
    log_error "Usage: $0 <vmid|hostname> [service-type]"
    log_info ""
    log_info "Examples:"
    log_info "  $0 1000              # Auto-detect service type"
    log_info "  $0 2500 validator    # Specify service type (validator/sentry/rpc)"
    log_info "  $0 validator-1       # Use hostname"
    log_info ""
    log_info "Service types: validator, sentry, rpc"
    log_info ""
    log_info "Note: Restarting Besu node clears the mempool."
    exit 1
fi

NODE_ID="$1"
SERVICE_TYPE="${2:-auto}"

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

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

# Get container hostname
HOSTNAME=$(pct config "$VMID" | grep "^hostname:" | awk '{print $2}' || echo "unknown")

log_info "========================================="
log_info "Restart Besu Node (Clears Mempool)"
log_info "========================================="
log_info ""
log_info "VMID: $VMID"
log_info "Hostname: $HOSTNAME"
log_info ""

# Detect service type if auto
if [[ "$SERVICE_TYPE" == "auto" ]]; then
    log_info "Auto-detecting service type..."
    
    # Check which service is active
    if pct exec "$VMID" -- systemctl is-active --quiet besu-validator.service 2>/dev/null; then
        SERVICE_TYPE="validator"
        SERVICE_NAME="besu-validator"
    elif pct exec "$VMID" -- systemctl is-active --quiet besu-sentry.service 2>/dev/null; then
        SERVICE_TYPE="sentry"
        SERVICE_NAME="besu-sentry"
    elif pct exec "$VMID" -- systemctl is-active --quiet besu-rpc.service 2>/dev/null; then
        SERVICE_TYPE="rpc"
        SERVICE_NAME="besu-rpc"
    else
        # Try to determine from hostname
        if echo "$HOSTNAME" | grep -qiE "validator|val"; then
            SERVICE_TYPE="validator"
            SERVICE_NAME="besu-validator"
        elif echo "$HOSTNAME" | grep -qiE "sentry|sent"; then
            SERVICE_TYPE="sentry"
            SERVICE_NAME="besu-sentry"
        elif echo "$HOSTNAME" | grep -qiE "rpc"; then
            SERVICE_TYPE="rpc"
            SERVICE_NAME="besu-rpc"
        else
            log_error "Cannot auto-detect service type. Please specify: validator, sentry, or rpc"
            exit 1
        fi
    fi
    
    log_info "Detected service type: $SERVICE_TYPE"
else
    # Use specified service type
    case "$SERVICE_TYPE" in
        validator)
            SERVICE_NAME="besu-validator"
            ;;
        sentry)
            SERVICE_NAME="besu-sentry"
            ;;
        rpc)
            SERVICE_NAME="besu-rpc"
            ;;
        *)
            log_error "Invalid service type: $SERVICE_TYPE (must be: validator, sentry, rpc)"
            exit 1
            ;;
    esac
fi

log_info "Service: $SERVICE_NAME"
log_info ""

# Check container status
CONTAINER_STATUS=$(pct status "$VMID" 2>/dev/null | awk '{print $2}' || echo "unknown")

if [[ "$CONTAINER_STATUS" != "running" ]]; then
    log_warn "Container $VMID is not running (status: $CONTAINER_STATUS)"
    log_info "Starting container..."
    pct start "$VMID" || log_error "Failed to start container"
    sleep 5
fi

# Check if service exists
if ! pct exec "$VMID" -- systemctl list-unit-files | grep -q "$SERVICE_NAME.service"; then
    log_error "Service $SERVICE_NAME.service not found on container $VMID"
    exit 1
fi

# Show current service status
log_info "Current service status:"
pct exec "$VMID" -- systemctl status "$SERVICE_NAME.service" --no-pager -l || true
log_info ""

# Warn about mempool clearing
log_warn "⚠️  Restarting Besu node will clear the mempool"
log_info "   All pending transactions will be removed"
log_info "   Node will resync with network"
log_info ""

# Confirm restart
read -p "Continue with restart? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    log_info "Restart cancelled"
    exit 0
fi

# Restart service
log_info "Restarting $SERVICE_NAME.service..."
if pct exec "$VMID" -- systemctl restart "$SERVICE_NAME.service"; then
    log_success "Service restart command executed"
else
    log_error "Failed to restart service"
    exit 1
fi

# Wait a moment for service to stop
sleep 3

# Check if service is starting
log_info "Waiting for service to start..."
sleep 5

# Verify service status
if pct exec "$VMID" -- systemctl is-active --quiet "$SERVICE_NAME.service" 2>/dev/null; then
    log_success "Service is active"
else
    log_warn "Service may not be fully started yet"
    log_info "Checking service status..."
    pct exec "$VMID" -- systemctl status "$SERVICE_NAME.service" --no-pager -l || true
fi

# Show recent logs
log_info ""
log_info "Recent service logs (last 20 lines):"
log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
pct exec "$VMID" -- journalctl -u "$SERVICE_NAME.service" -n 20 --no-pager || true
log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

log_info ""
log_success "Besu node restart completed!"
log_info ""
log_info "Note: Mempool has been cleared. The node will:"
log_info "  - Resync with the network"
log_info "  - Rebuild peer connections"
log_info "  - Start processing new transactions"
log_info ""
log_info "Monitor logs with:"
log_info "  pct exec $VMID -- journalctl -u $SERVICE_NAME.service -f"
log_info ""

