#!/usr/bin/env bash
# Installation script for Besu Sentry Node in LXC container

set -euo pipefail

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

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"

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"; }

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"

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

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"

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"

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

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

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

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

Restart=always
RestartSec=10

LimitNOFILE=65536
LimitNPROC=32768

NoNewPrivileges=true
PrivateTmp=true

StandardOutput=journal
StandardError=journal
SyslogIdentifier=besu-sentry

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
log_success "Systemd service created"

log_info "Creating configuration template..."
cat > "$BESU_CONFIG/config-sentry.toml.template" <<'EOF'
# Besu Configuration for Sentry Nodes
data-path="/data/besu"
genesis-file="/etc/besu/genesis.json"

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

miner-enabled=false

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

# RPC Configuration (internal only)
rpc-http-enabled=true
rpc-http-host="0.0.0.0"
rpc-http-port=8545
rpc-http-api=["ETH","NET","WEB3","ADMIN"]
rpc-http-cors-origins=["*"]
rpc-http-host-allowlist=["*"]

rpc-ws-enabled=true
rpc-ws-host="0.0.0.0"
rpc-ws-port=8546
rpc-ws-api=["ETH","NET","WEB3"]

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

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

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

tx-pool-max-size=8192
tx-pool-price-bump=10
tx-pool-retention-hours=6

static-nodes-file="/etc/besu/static-nodes.json"

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"

systemctl enable besu-sentry.service

log_success "Besu Sentry installation completed!"

