#!/usr/bin/env bash

# Exit script as soon as a command fails.
set -o errexit

testrpc_port=8545

testrpc_running() {
  nc -z localhost "$testrpc_port"
}

kill_testrpc() {
  lsof -ti:8545 -sTCP:LISTEN | xargs kill
}

cleanup() {
  printf "\nCleaning up..."    
  rm -rf polymath-core || true
  rm -rf ../polymath-core || true
  kill_testrpc
}

trap cleanup EXIT

rm -rf node_modules || true
rm -rf artifacts || true
rm -rf blockchain-state || true
mkdir blockchain-state
mkdir blockchain-state/2.1.0
mkdir blockchain-state/3.0.0
mkdir blockchain-state/3.1.0
mkdir artifacts

git clone git@github.com:PolymathNetwork/polymath-core.git

cd polymath-core
rm -rf build || true
rm -rf build_old || true
rm -rf build_new || true
git checkout dev-2-snapshot
rm -rf node_modules || true
yarn

start_testrpc() {
  node_modules/.bin/ganache-cli --networkId=15 --gasLimit=90000000 --mnemonic="candy maple cake sugar pudding cream honey rich smooth crumble sweet treat" --accounts=500 --db="../blockchain-state/$1" > /dev/null &

  testrpc_pid=$!
}

if testrpc_running; then
  echo "Using existing testrpc instance"
else
  echo "Starting our own testrpc instance"
  start_testrpc "2.1.0"
fi

echo "Deploying polymath-core 2.1"
node_modules/.bin/truffle deploy

mv build build_2.1.0

kill_testrpc

git stash
git checkout dev-3.0.0
rm -rf node_modules || true
yarn

echo "Restarting our own testrpc instance"
start_testrpc "3.0.0"

echo "Deploying polymath-core 3.0"
node_modules/.bin/truffle deploy

mv build build_3.0.0

kill_testrpc

git stash
git checkout dev-3.1.0
rm -rf node_modules || true
yarn

echo "Restarting our own testrpc instance"
start_testrpc "3.1.0"

echo "Deploying polymath-core 3.1"
yarn compile && yarn migrate:local

kill_testrpc

mv build/contracts ../artifacts/3.1.0

mv build_3.0.0/contracts ../artifacts/3.0.0

mv build_2.1.0/contracts ../artifacts/2.1.0

cd ..
yarn