#!/bin/bash

# Ensure jq is installed
if [[ ! -x "$(which jq)" ]]; then
  echo "jq (a tool for parsing json in the command line) is required..."
  echo "https://stedolan.github.io/jq/download/"
  exit 1
fi

# Ensure docker is installed
if [[ ! -x "$(which docker-compose)" ]]; then
  echo "docker (a containerization tool) is required..."
  echo "https://docs.docker.com/compose/install/"
  exit 1
fi

RELAYER_DIR="$GOPATH/src/github.com/iqlusioninc/relayer"
RELAYER_CONF="$HOME/.relayer"
ENV_FILE="$RELAYER_DIR/.env"

# Ensure user understands what will be deleted
if [[ -d $RELAYER_CONF ]] && [[ ! "$1" == "skip" ]]; then
  read -p "$0 will delete ~/.relayer folder and \$(pwd)/.env file. Do you wish to continue? (y/n): " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
      exit 1
  fi
fi

echo "Stopping any existing containers..."
docker-compose down &> /dev/null

cd $RELAYER_DIR
rm -rf $RELAYER_CONF &> /dev/null
rm -rf $ENV_FILE &> /dev/null
touch $ENV_FILE

make install

echo "Generating rly configurations..."
rly cfg i

echo "Adding configuration..."
rly cfg ad configs/four/ &> /dev/null

echo "Generating keys..."
echo "IBC0ADDR=$(rly k a ibc0 | jq -r '.address')" >> $ENV_FILE
echo "IBC1ADDR=$(rly k a ibc1 | jq -r '.address')" >> $ENV_FILE
echo "IBC2ADDR=$(rly k a ibc2 | jq -r '.address')" >> $ENV_FILE
echo "IBC3ADDR=$(rly k a ibc3 | jq -r '.address')" >> $ENV_FILE

echo "Creating containers..."
docker-compose up -d &> /dev/null

echo "Waiting for blocks..."
sleep 8

echo "Creating lite clients for chains..."
rly lite init ibc0 -f
rly lite init ibc1 -f
rly lite init ibc2 -f
rly lite init ibc3 -f

echo "Starting 'rly tx link zeroone' (ibc0<>ibc1) logs in data/zeroone.log"
rly tx link zeroone -d -o 3s 2>&1 > data/zeroone.log &
sleep 1
echo "Starting 'rly tx link twothree' (ibc2<>ibc3) logs in data/twothree.log"
rly tx link twothree -d -o 3s 2>&1 > data/twothree.log &
sleep 1
echo "Starting 'rly tx link onetwo' (ibc1<>ibc2) logs in data/onetwo.log"
rly tx link onetwo -d -o 3s 2>&1 > data/onetwo.log &
sleep 2
echo "Starting 'rly tx link threezero' (ibc3<>ibc0) logs in data/threezero.log"
rly tx link threezero -d -o 3s 2>&1 > data/threezero.log &
sleep 1
echo "Check the state of the connections using 'rly paths list' to see when they are ready to relay over..."
rly paths list