#!/bin/sh
set -e

# Initialize if needed
if [ ! -d "/work/xdcchain/XDC/chaindata" ]; then
    echo "Initializing mainnet chaindata..."
    XDC init --datadir /work/xdcchain /work/config/genesis.json
fi

# Load bootnodes
if [ -f "/work/config/bootnodes.list" ]; then
    BOOTNODES=$(cat /work/config/bootnodes.list | tr "\n" "," | sed "s/,$//")
fi

# Get external IP
EXTERNAL_IP=$(wget -qO- https://checkip.amazonaws.com 2>/dev/null || echo "")

echo "Starting XDC Mainnet PBSS..."
exec XDC \
  --datadir /work/xdcchain \
  --networkid 50 \
  --port 30303 \
  --syncmode full \
  --state.scheme path \
  --gcmode full \
  --verbosity 3 \
  --cache 4096 \
  --maxpeers 50 \
  --bootnodes "$BOOTNODES" \
  ${EXTERNAL_IP:+--nat extip:$EXTERNAL_IP} \
  --http --http.addr 0.0.0.0 --http.port 8545 \
  --http.api admin,eth,net,web3,xdpos \
  --http.corsdomain "*" --http.vhosts "*" \
  --ws --ws.addr 0.0.0.0 --ws.port 8546 \
  --ws.api eth,net,web3 --ws.origins "*"
