#!/bin/bash

SCRIPT=`realpath $0`
SCRIPTPATH=`dirname $SCRIPT`

DATADIR="${SCRIPTPATH}/datadir"

HIVED="${SCRIPTPATH}/bin/hived"

ARGS=""

# to help handling maintenance issues
if [[ -e ${DATADIR}/blockchain/stop ]]; then
  echo "blockchain/stop exists so refusing to start"
  sleep 60
  exit 1
fi

if [[ -e ${DATADIR}/blockchain/force_replay ]]; then
  echo "We will force replay this time"
  rm -fv ${DATADIR}/blockchain/force_replay
  ARGS+=" --replay-blockchain --force-replay --set-benchmark-interval 100000"
fi

if [[ -e ${DATADIR}/blockchain/force_open ]]; then
  echo "We will force open this time"
  rm -fv ${DATADIR}/blockchain/force_open
  ARGS+=" --force-open"
fi

if [[ -e ${DATADIR}/blockchain/load_snapshot ]]; then
  echo "We will load latest snapshot"
  rm -fv ${DATADIR}/blockchain/load_snapshot
  ARGS+=" --load-snapshot latest"
fi

if [[ ! -z "$TRACK_ACCOUNT" ]]; then
    ARGS+=" --plugin=account_history_rocksdb --plugin=account_history_api"
    ARGS+=" --account-history-rocksdb-track-account-range=[\"$TRACK_ACCOUNT\",\"$TRACK_ACCOUNT\"]"
fi

if [[ "$USE_PUBLIC_BLOCKLOG" ]]; then
  if [[ ! -e ${DATADIR}/blockchain/block_log ]]; then
    if [[ ! -d ${DATADIR}/blockchain ]]; then
      mkdir -p ${DATADIR}/blockchain
    fi
    echo "Hived: Downloading a block_log and replaying the blockchain"
    echo "This may take a little while..."
    wget -O ${DATADIR}/blockchain/block_log https://gtg.openhive.network/get/blockchain/block_log
    ARGS+=" --replay-blockchain"
  fi
fi

echo ARGS $ARGS

"$HIVED" \
  --webserver-ws-endpoint=0.0.0.0:8090 \
  --webserver-http-endpoint=0.0.0.0:8090 \
  --p2p-endpoint=0.0.0.0:2001 \
  --data-dir="${DATADIR}" \
  $ARGS \
  2>&1
