#!/bin/bash
# make-chain.sh: build a regtest chain of the same shape every time (same heights, balances and
# amounts; new keys and timestamps, so new hashes). For byte-identical chains, snapshot the folder.
# Usage: ./make-chain.sh <datadir> <p2p-port> <rpc-port>
set -e
DIR=${1:?datadir}; PORT=${2:?p2p port}; RPCPORT=${3:?rpc port}
DIVID=${DIVID:-$HOME/divi-3.0.0/bin/divid}
CLI=${CLI:-$HOME/divi-3.0.0/bin/divi-cli}

# Only ever delete a folder this script made before (regtest=1 in its divi.conf) or an empty one.
if [ -e "$DIR" ] && [ -n "$(ls -A "$DIR")" ] && ! grep -qx 'regtest=1' "$DIR/divi.conf" 2>/dev/null; then
  echo "refusing to delete $DIR: it is not empty and has no regtest divi.conf" >&2; exit 1
fi
rm -rf "$DIR"; mkdir -p "$DIR"
PW=$(head -c 32 /dev/urandom | base64 | tr -d '/+=' | head -c 40)
cat > "$DIR/divi.conf" <<CONF
regtest=1
server=1
listen=1
bind=127.0.0.1
rpcbind=127.0.0.1
rpcallowip=127.0.0.1
port=$PORT
rpcport=$RPCPORT
rpcuser=regtest
rpcpassword=$PW
staking=0
CONF
chmod 600 "$DIR/divi.conf"
cli() { "$CLI" -datadir="$DIR" "$@"; }

nohup "$DIVID" -datadir="$DIR" >/dev/null 2>&1 </dev/null &
NODE=$!
until cli getblockcount >/dev/null 2>&1; do
  kill -0 $NODE 2>/dev/null || { echo "divid exited: see $DIR/regtest/debug.log (port $PORT or $RPCPORT already in use?)" >&2; exit 1; }
  sleep 1
done

cli setgenerate 101 >/dev/null                # blocks 1-101: 100,000 DIVI spendable
ALICE=$(cli getnewaddress)
BOB=$(cli getnewaddress)
TX1=$(cli sendtoaddress "$ALICE" 500)
cli setgenerate 1 >/dev/null                  # block 102 confirms TX1
TX2=$(cli sendtoaddress "$BOB" 250)
cli setgenerate 5 >/dev/null                  # blocks 103-107, TX2 is in 103 (5 confirmations)

echo "height    $(cli getblockcount)"
echo "balance   $(cli getbalance)"
echo "alice     $(cli getreceivedbyaddress "$ALICE") in $TX1 ($(cli gettransaction "$TX1" | grep -m1 '"confirmations"' | tr -d ' ,'))"
echo "bob       $(cli getreceivedbyaddress "$BOB") in $TX2 ($(cli gettransaction "$TX2" | grep -m1 '"confirmations"' | tr -d ' ,'))"
echo "tip hash  $(cli getbestblockhash)"
echo "genesis   $(cli getblockhash 0)"
