#!/usr/bin/env bash
# Installation script for Besu Validator Node in LXC container
# This script installs and configures Hyperledger Besu validator node

set -euo pipefail

source /dev/stdin <<<"$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func 2>/dev/null || echo '')"

# Default values
BESU_VERSION="${BESU_VERSION:-23.10.0}"
BESU_USER="${BESU_USER:-besu}"
BESU_GROUP="${BESU_GROUP:-besu}"
BESU_HOME="/opt/besu"
BESU_DATA="/data/besu"
BESU_CONFIG="/etc/besu"
BESU_LOGS="/var/log/besu"

# Color codes
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}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Update system
log_info "Updating system packages..."
export LC_ALL=C
export LANG=C
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get upgrade -y -qq
apt-get install -y -qq \
    openjdk-17-jdk \
    wget \
    curl \
    jq \
    netcat-openbsd \
    iproute2 \
    iptables \
    ca-certificates \
    gnupg \
    lsb-release

log_success "System packages updated"

# Create besu user
log_info "Creating besu user..."
if ! id -u "$BESU_USER" &>/dev/null; then
    useradd -r -s /bin/bash -d "$BESU_HOME" -m "$BESU_USER"
    log_success "Created besu user"
else
    log_info "Besu user already exists"
fi

# Download and install Besu
log_info "Installing Hyperledger 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"

if [[ ! -d "$BESU_HOME" ]]; then
    mkdir -p "$BESU_HOME"
fi

wget -q "$BESU_DOWNLOAD_URL" -O "$BESU_TAR" || {
    log_error "Failed to download Besu"
    exit 1
}

tar -xzf "$BESU_TAR" -C "$BESU_HOME" --strip-components=1
rm -f "$BESU_TAR"

chown -R "$BESU_USER:$BESU_GROUP" "$BESU_HOME"
chmod +x "$BESU_HOME/bin/besu"

log_success "Besu installed"

# Create directories
log_info "Creating directories..."
mkdir -p "$BESU_DATA" "$BESU_CONFIG" "$BESU_LOGS"
chown -R "$BESU_USER:$BESU_GROUP" "$BESU_DATA" "$BESU_CONFIG" "$BESU_LOGS"

log_success "Directories created"

# Create systemd service
log_info "Creating systemd service..."
cat > /etc/systemd/system/besu-validator.service <<EOF
[Unit]
Description=Hyperledger Besu Validator Node
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=$BESU_USER
Group=$BESU_GROUP
WorkingDirectory=$BESU_HOME

# Environment
Environment="BESU_OPTS=-Xmx4g -Xms4g"
Environment="JAVA_OPTS=-XX:+UseG1GC -XX:MaxGCPauseMillis=200"

# ExecStart
ExecStart=$BESU_HOME/bin/besu \\
    --config-file=$BESU_CONFIG/config-validator.toml

# Restart
Restart=always
RestartSec=10

# Resource limits
LimitNOFILE=65536
LimitNPROC=32768

# Security
NoNewPrivileges=true
PrivateTmp=true

# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=besu-validator

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
log_success "Systemd service created"

# Create configuration file template (will be updated by deployment script)
log_info "Creating configuration template..."
cat > "$BESU_CONFIG/config-validator.toml.template" <<'EOF'
# Besu Configuration for Validator Nodes
data-path="/data/besu"
genesis-file="/etc/besu/genesis.json"

network-id=138
p2p-host="0.0.0.0"
p2p-port=30303

# QBFT Consensus
miner-enabled=false
miner-coinbase="0x0000000000000000000000000000000000000000"

sync-mode="FULL"
fast-sync-min-peers=2

# RPC Configuration (DISABLED for validators)
rpc-http-enabled=false
rpc-ws-enabled=false

# Metrics
metrics-enabled=true
metrics-port=9545
metrics-host="0.0.0.0"
metrics-push-enabled=false

# Logging
logging="INFO"
log-destination="CONSOLE"

# Permissioning
permissions-nodes-config-file-enabled=true
permissions-nodes-config-file="/etc/besu/permissions-nodes.toml"
permissions-accounts-config-file-enabled=true
permissions-accounts-config-file="/etc/besu/permissions-accounts.toml"

# Transaction Pool
tx-pool-max-size=4096
tx-pool-price-bump=10

# Static Nodes
static-nodes-file="/etc/besu/static-nodes.json"

# Discovery
discovery-enabled=true

privacy-enabled=false

database-path="/data/besu/database"
trie-logs-enabled=false

rpc-tx-feecap="0x0"
accounts-enabled=false

max-peers=25
max-remote-initiated-connections=10
EOF

log_success "Configuration template created"

# Enable service (but don't start yet - will start after configuration)
systemctl enable besu-validator.service

log_success "Besu Validator installation completed!"
log_info "Next steps:"
log_info "1. Copy configuration files to $BESU_CONFIG/"
log_info "2. Copy genesis.json to $BESU_CONFIG/genesis.json"
log_info "3. Copy static-nodes.json to $BESU_CONFIG/static-nodes.json"
log_info "4. Copy validator keys to /keys/ directory"
log_info "5. Start service: systemctl start besu-validator"

