#!/bin/sh
# tacchaind entrypoint — TAC (Cosmos-SDK + embedded EVM). Genesis replay is impractical
# (5 gov upgrades), so fresh nodes statesync near head via cometbft-common.sh.
set -e
. /usr/local/bin/cometbft-common.sh

HOME_DIR="/root/.tacchaind"
CONFIG_DIR="$HOME_DIR/config"
CHAIN_ID="${CHAIN_ID:-tacchain_239-1}"
GENESIS_URL="${GENESIS_URL:-https://raw.githubusercontent.com/TacBuild/tacchain/refs/heads/main/networks/tacchain_239-1/genesis.json}"
STATESYNC_RPC="${STATESYNC_RPC:-https://tacchain-rpc.polkachu.com:443}"
MIN_GAS="${MIN_GAS:-25000000000utac}"
API="${API:-eth,net,web3,txpool,debug}"
MONIKER="${MONIKER:-rpc-node}"

ct_apk curl jq

if tacchaind 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

# Serve CometBFT 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"

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"

sed -i -e "s/^indexer *=.*/indexer = \"null\"/" "$CONFIG_DIR/config.toml"

sed -i "/^\[json-rpc\]/,/^\[/{s|^address = .*|address = \"0.0.0.0:8545\"|}" "$CONFIG_DIR/app.toml"
sed -i "/^\[json-rpc\]/,/^\[/{s|^ws-address = .*|ws-address = \"0.0.0.0:8546\"|}" "$CONFIG_DIR/app.toml"
sed -i "/^\[json-rpc\]/,/^\[/{s|^api = .*|api = \"$API\"|}" "$CONFIG_DIR/app.toml"

ct_seed_priv_validator_state "$HOME_DIR"

exec tacchaind start --chain-id="$CHAIN_ID" --pruning=default --json-rpc.enable --home "$HOME_DIR" "$@"
