#!/bin/sh
# babylon-genesis (babylond) entrypoint — family C, pure CometBFT (no EL). Thin: sources the
# shared cometbft-common.sh and orchestrates init + statesync bootstrap + start.
# Genesis replay is impractical; statesync near head with the current binary.
# Serves CometBFT RPC :26657 (the dshackle upstream).
set -e
. /usr/local/bin/cometbft-common.sh

HOME_DIR="/root/.babylond"
CONFIG_DIR="$HOME_DIR/config"
CHAIN_ID="${CHAIN_ID:-bbn-1}"
GENESIS_URL="${GENESIS_URL:-https://raw.githubusercontent.com/babylonlabs-io/networks/main/bbn-1/network-artifacts/genesis.json}"
STATESYNC_RPC="${STATESYNC_RPC:-https://babylon-rpc.polkachu.com:443}"
MIN_GAS="${MIN_GAS:-0.002ubbn}"
MONIKER="${MONIKER:-rpc-node}"

ct_apk curl jq

if babylond init "$MONIKER" --chain-id "$CHAIN_ID" --home "$HOME_DIR" >/dev/null 2>&1; then
  ct_log "fresh init; fetching genesis"
  ct_fetch "$GENESIS_URL" "$CONFIG_DIR/genesis.json" required
  ct_localize_home "$CONFIG_DIR"
  ct_set_min_gas_prices "$CONFIG_DIR/app.toml" "$MIN_GAS"
else
  ct_log "already initialized, continuing"
fi

# v4.x start prompts for a BLS password if no key exists; RPC replicas never sign
# checkpoints, so pre-create an empty-password key before the first start.
if [ ! -f "$CONFIG_DIR/bls_key.json" ]; then
  ct_log "pre-creating BLS key (no password — RPC replica)"
  babylond create-bls-key --home "$HOME_DIR" --no-bls-password
fi

# Serve RPC on all interfaces (dshackle/traefik upstream); default is 127.0.0.1.
sed -i '/^\[rpc\]/,/^\[/{s|^laddr = .*|laddr = "tcp://0.0.0.0:26657"|}' "$CONFIG_DIR/config.toml"

# Babylon Genesis block time (9200ms) — required for consensus.
sed -i 's|^timeout_commit = .*|timeout_commit = "9200ms"|' "$CONFIG_DIR/config.toml"

# BTC checkpointing network params only — no bitcoind needed for an RPC replica.
sed -i '/^\[btc-config\]/,/^\[/{s|^network = .*|network = "mainnet"|}' "$CONFIG_DIR/app.toml"

# Recommended for pruned RPC nodes (reduces memory pressure).
sed -i 's|^iavl-cache-size = .*|iavl-cache-size = 0|' "$CONFIG_DIR/app.toml"

ct_patch_p2p             "$CONFIG_DIR/config.toml" "$IP" "${P2P_PORT:-26656}"
ct_merge_seeds           "$CONFIG_DIR/config.toml" "$SEEDS"
ct_set_persistent_peers  "$CONFIG_DIR/config.toml" "$PERSISTENT_PEERS"
ct_set_moniker           "$CONFIG_DIR/config.toml" "$MONIKER"
ct_configure_statesync   "$CONFIG_DIR/config.toml" "$STATESYNC_RPC"
ct_ensure_wasm           "$HOME_DIR" "$WASM_SNAPSHOT_URL"
ct_seed_priv_validator_state "$HOME_DIR"

exec babylond start --home "$HOME_DIR" --minimum-gas-prices "$MIN_GAS" --no-bls-password "$@"
