#!/bin/bash
set -e

# ============================================================
# init-fullnode.sh — 初始化非创世全节点 (从创世节点同步)
#
# 用法: 由 Docker 容器内执行，需要挂载:
#   -v <genesis-volume>:/genesis:ro   (创世节点的 .genexd 目录)
#   -v <node-volume>:/home/genex/.genexd
#
# 环境变量:
#   MONIKER       — 节点名称 (必填)
#   CHAIN_ID      — 链ID (默认: genex-testnet-1)
#   PEERS         — 持久对等节点列表 (node_id@host:port)
# ============================================================

CHAIN_ID="${CHAIN_ID:-genex-testnet-1}"
HOME_DIR="/home/genex/.genexd"
GENESIS_SOURCE="/genesis/config/genesis.json"

if [ -z "$MONIKER" ]; then
    echo "[ERROR] MONIKER environment variable is required"
    exit 1
fi

echo "[1/4] Initializing node: $MONIKER ..."
genexd init "$MONIKER" --chain-id "$CHAIN_ID" --home "$HOME_DIR" > /dev/null 2>&1

echo "[2/4] Copying genesis.json from genesis node..."
if [ ! -f "$GENESIS_SOURCE" ]; then
    echo "[ERROR] Genesis file not found at $GENESIS_SOURCE"
    exit 1
fi
cp "$GENESIS_SOURCE" "$HOME_DIR/config/genesis.json"

echo "[3/4] Configuring node..."
CONFIG_TOML="$HOME_DIR/config/config.toml"
APP_TOML="$HOME_DIR/config/app.toml"

# Persistent peers
if [ -n "$PEERS" ]; then
    sed -i "s/persistent_peers = \"\"/persistent_peers = \"$PEERS\"/" "$CONFIG_TOML"
fi

# RPC 监听 (允许外部访问)
sed -i "s/laddr = \"tcp:\/\/127.0.0.1:26657\"/laddr = \"tcp:\/\/0.0.0.0:26657\"/" "$CONFIG_TOML"
sed -i "s/cors_allowed_origins = \[\]/cors_allowed_origins = [\"*\"]/" "$CONFIG_TOML"

# 共识参数 (与创世节点一致)
sed -i 's/timeout_propose = "3s"/timeout_propose = "1500ms"/' "$CONFIG_TOML"
sed -i 's/timeout_propose_delta = "500ms"/timeout_propose_delta = "200ms"/' "$CONFIG_TOML"
sed -i 's/timeout_prevote = "1s"/timeout_prevote = "500ms"/' "$CONFIG_TOML"
sed -i 's/timeout_prevote_delta = "500ms"/timeout_prevote_delta = "200ms"/' "$CONFIG_TOML"
sed -i 's/timeout_precommit = "1s"/timeout_precommit = "500ms"/' "$CONFIG_TOML"
sed -i 's/timeout_precommit_delta = "500ms"/timeout_precommit_delta = "200ms"/' "$CONFIG_TOML"
sed -i 's/timeout_commit = "5s"/timeout_commit = "1s"/' "$CONFIG_TOML"

# app.toml — 启用 API / JSON-RPC
sed -i "/\[api\]/,/\[/ s/enable = false/enable = true/" "$APP_TOML"
sed -i "/\[json-rpc\]/,/\[/ s/enable = false/enable = true/" "$APP_TOML"
sed -i "s/address = \"127.0.0.1:8545\"/address = \"0.0.0.0:8545\"/" "$APP_TOML"
sed -i "s/ws-address = \"127.0.0.1:8546\"/ws-address = \"0.0.0.0:8546\"/" "$APP_TOML"
sed -i "s/minimum-gas-prices = \"\"/minimum-gas-prices = \"0agnx\"/" "$APP_TOML"
sed -i "s/iavl-cache-size = 781250/iavl-cache-size = 2000000/" "$APP_TOML"

echo "[4/4] Node initialized!"
echo "  Moniker: $MONIKER"
echo "  Chain:   $CHAIN_ID"
echo "  Peers:   ${PEERS:-none}"
echo "  Home:    $HOME_DIR"
