#!/bin/bash  -e
# launch bundler: also start geth, and deploy entrypoint.
cd `dirname $0`

GETH=geth
GETHPORT=8545
BUNDLERPORT=3000
GETHPID=/tmp/aabundler.geth.pid
BUNDLERPID=/tmp/aabundler.node.pid
VERSION="aabundler-js-0.1"

BUNDLERLOG=/tmp/aabundler.log

BUNDLERURL=http://localhost:$BUNDLERPORT/rpc
NODEURL=http://localhost:$GETHPORT

function fatal {
  echo "$@" 1>&2
  exit 1
}

function isPortFree {
  port=$1
  curl http://localhost:$port 2>&1 | grep -q Connection.refused
}


function waitForPort {
  port=$1
  while isPortFree $port; do true; done
}

function startBundler {

isPortFree $GETHPORT || fatal port $GETHPORT not free
isPortFree $BUNDLERPORT || fatal port $BUNDLERPORT not free

echo == starting geth 1>&2
$GETH version | grep ^Version: 1>&2

$GETH --dev --http.port $GETHPORT \
        --http.api personal,eth,net,web3,debug \
        --ignore-legacy-receipts \
        --http \
        --http.addr "0.0.0.0" \
        --rpc.allow-unprotected-txs \
        --allow-insecure-unlock \
        --verbosity 1  & echo $! > $GETHPID

waitForPort $GETHPORT

cd packages/bundler
echo == Deploying entrypoint 1>&2
export TS_NODE_TRANSPILE_ONLY=1
npx hardhat deploy --network localhost
echo == Starting bundler 1>&2
ts-node -T ./src/exec.ts --config ./localconfig/bundler.config.json --port $BUNDLERPORT --network http://localhost:$GETHPORT  & echo $! > $BUNDLERPID
waitForPort $BUNDLERPORT
}

function start {
  isPortFree $GETPORTPORT || fatal port $GETHPORT not free
  isPortFree $BUNDLERPORT || fatal port $BUNDLERPORT not free
  startBundler > $BUNDLERLOG
  echo == Bundler, Geth started. log to $BUNDLERLOG
}

function stop {
  echo == stopping bundler
  test -r $BUNDLERPID && kill -9 `cat $BUNDLERPID`
  test -r $GETHPID && kill -9 `cat $GETHPID`
  rm $BUNDLERPID $GETHPID
  echo == bundler, geth stopped
}

function jsoncurl {
  method=$1
  params=$2
  url=$3
  data="{\"method\":\"$method\",\"params\":$params,\"id\":1,\"jsonrpc\":\"2.0\"}"
  curl -s -H content-type:application/json -d $data $url
}

function info {
  entrypoint=`jsoncurl eth_supportedEntryPoints [] $BUNDLERURL | jq -r .result["0"]`
  echo "BUNDLER_ENTRYPOINT=$entrypoint"
  status="down"; test -n "$entrypoint" && status="active"
  echo "BUNDLER_URL=$BUNDLERURL"
  echo "BUNDLER_NODE_URL=$NODEURL"
  echo "BUNDLER_LOG=$BUNDLERLOG"
  echo "BUNDLER_VERSION=$VERSION"
  echo "BUNDLER_STATUS=$status"
}

case $1 in

 start)
	start
	;;
 stop)
 	stop
	;;

  restart)
	echo == restarting bundler
	stop
	start
	;;

  info)
    info
    ;;

 *) echo "usage: $0 {start|stop|restart|info}"
    exit 1 ;;


esac
