#!/bin/sh
# Shibarium heimdall node entrypoint — thin bootstrap sourcing cometbft-common.sh.
# 
# Bootstraps a heimdalld node:
#   1. source cometbft-common.sh for helpers (ct_*)
#   2. heimdalld init with moniker + chain-id
#   3. fetch genesis.json from GENESIS_URL if set
#   4. patch p2p config (bind 0.0.0.0:PORT, external_address)
#   5. merge seeds from env SEEDS + optional official seed list
#   6. set persistent_peers from env PERSISTENT_PEERS
#   7. enable REST server on :1317
#   8. bind CometBFT RPC to 0.0.0.0:26657
#   9. exec heimdalld start --home $CMT_HOME --chain <chain> --rest-server
#
# Environment:
#   CMT_HOME       heimdall home dir (default /root/.heimdalld)
#   CHAIN_ID       shibarium chain id (109 -> mainnet)
#   GENESIS_URL    URL to fetch genesis.json
#   SEEDS          comma-separated seed nodes (optional)
#   PERSISTENT_PEERS comma-separated persistent peers (optional)
#   IP             external IP for p2p advertisement
#   MONIKER        node moniker (default d${DOMAIN:-local})
#   P2P_PORT       p2p port (default 26656)
#
# NOTE: heimdall (bone fork) merged REST/LCD into the daemon, so REST runs
# in-process via --rest-server flag. No separate rest-server subcommand needed.

set -e

# Source the shared CometBFT helpers
. /usr/local/bin/cometbft-common.sh

CMT_HOME="${CMT_HOME:-/root/.heimdalld}"
CHAIN_ID="${CHAIN_ID:-heimdall-109}"
CHAIN="${CHAIN:-shibarium}"
P2P_PORT="${P2P_PORT:-26656}"
MONIKER="${MONIKER:-d${DOMAIN:-local}}"
# Shibarium heimdall mainnet seeds (verified from shibaone/node-ansible branch shibarium)
# These are the persistent peers that match the bor bootnodes
PERSISTENT_PEERS="${PERSISTENT_PEERS:-96f333f77d5e2f877d3afe4a3643e4f99949ef5c@44.204.200.100:26656,e6676c16d8a9ec98bbbce8d137a3765632720328@18.136.201.99:26656,8c71c016de039e50e48f74683784054f46bd0a1c@3.99.233.157:26656,fb613910f04f0ae0001d93b70552d4d5c358ad78@63.32.53.219:26656,08c3509327941a593eef258f23ab568c10d28905@52.12.214.141:26656}"

ct_log "Starting heimdalld bootstrap for chain ${CHAIN_ID} (home=${CMT_HOME})"

# Ensure home dir exists
mkdir -p "$CMT_HOME/config" "$CMT_HOME/data"

# Self-heal: earlier builds injected `rest_server = true` into config.toml on EVERY
# boot (non-idempotent), accumulating duplicates until heimdalld died on
# "toml: key rest_server is already defined". rest_server is not a valid CometBFT
# config.toml key — REST is enabled by --rest-server in the start command — so strip
# any previously-injected copies before heimdalld reads the config.
if [ -f "$CMT_HOME/config/config.toml" ]; then
  sed -i '/^rest_server = true$/d' "$CMT_HOME/config/config.toml"
fi

# Step 1: heimdalld init — FIRST BOOT ONLY. Re-initializing an existing home resets
# node identity/state and re-parses the existing config; guard on config.toml.
if [ ! -f "$CMT_HOME/config/config.toml" ]; then
  ct_log "First boot: heimdalld init --home $CMT_HOME --chain $CHAIN"
  heimdalld init --home "$CMT_HOME" --chain "$CHAIN"
  sed -i '/^rest_server = true$/d' "$CMT_HOME/config/config.toml" 2>/dev/null || true
else
  ct_log "Already initialized — skipping heimdalld init"
fi

# Step 2: Fetch the shibarium (heimdall-109) genesis if GENESIS_URL is set (idempotent).
if [ -n "$GENESIS_URL" ]; then
  ct_log "Fetching genesis from $GENESIS_URL"
  ct_fetch "$GENESIS_URL" "$CMT_HOME/config/genesis.json" required
fi

# Step 3: Patch config.toml p2p settings
ct_patch_p2p "$CMT_HOME/config/config.toml" "$IP" "$P2P_PORT"

# Step 4: Merge seeds from SEEDS env var (comma-separated) + optional official list
ct_merge_seeds "$CMT_HOME/config/config.toml" "$SEEDS"

# Step 5: Set persistent peers if provided
ct_set_persistent_peers "$CMT_HOME/config/config.toml" "$PERSISTENT_PEERS"

# Step 6: Set moniker
ct_set_moniker "$CMT_HOME/config/config.toml" "$MONIKER"

# Step 7: Localize home paths (~/ -> /root/)
ct_localize_home "$CMT_HOME/config"

# Step 8: Enable REST server on 1317 and bind CometBFT RPC to 0.0.0.0:26657
# heimdalld (bone fork) uses --rest-server flag to enable in-process REST/LCD.
# The config.toml rpc settings are for CometBFT RPC (26657), not REST.
# REST is configured via --rest-server.addr flag in the start command.

# Configure CometBFT RPC to bind to all interfaces on 26657
ct_log "Configuring CometBFT RPC on 0.0.0.0:26657"
if [ -f "$CMT_HOME/config/config.toml" ]; then
  sed -i 's|^rpc_laddr = .*|rpc_laddr = "tcp://0.0.0.0:26657"|' "$CMT_HOME/config/config.toml"
  sed -i 's|^cors_allowed_origins = .*|cors_allowed_origins = ["*" ]|' "$CMT_HOME/config/config.toml"
  sed -i 's|^cors_allowed_methods = .*|cors_allowed_methods = ["HEAD", "GET", "POST", "OPTIONS"]|' "$CMT_HOME/config/config.toml"
  sed -i 's|^cors_allowed_headers = .*|cors_allowed_headers = ["Origin", "Accept", "Content-Type", "X-Requested-With", "X-Server-Time"]|' "$CMT_HOME/config/config.toml"
  # NOTE: do NOT inject `rest_server` / `rest_server_addr` into config.toml. REST/LCD
  # is enabled by the --rest-server / --rest-server.addr flags in the start command
  # below; injecting the key duplicates one heimdalld already defines and crashes it
  # with "toml: key rest_server is already defined".
fi

# Step 9: Seed priv_validator_state if present in config
ct_seed_priv_validator_state "$CMT_HOME"

ct_log "Bootstrap complete. Starting heimdalld..."

# Start heimdalld with the in-process REST/LCD server enabled.
# --rest-server  enables the REST/LCD server
# --laddr        REST/LCD listen address (default tcp://0.0.0.0:1317) — NOT
#                --rest-server.addr, which this heimdall build rejects as an
#                "unknown flag".
# --rpc.laddr    CometBFT RPC listen address (default is 127.0.0.1 — bind 0.0.0.0)
# --p2p.laddr    P2P listen address on the salted P2P_PORT
exec heimdalld start \
  --home "$CMT_HOME" \
  --chain "$CHAIN" \
  --rest-server \
  --laddr=tcp://0.0.0.0:1317 \
  --rpc.laddr=tcp://0.0.0.0:26657 \
  --p2p.laddr=tcp://0.0.0.0:$P2P_PORT
