#/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

RELAYER_DIR="$GOPATH/src/github.com/iqlusioninc/relayer"
RELAYER_CONF="$HOME/.relayer"
GAIA_CONF="$RELAYER_DIR/data"

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

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

echo "Building Relayer..."
make install

echo "Generating rly configurations..."
rly config init
rly config add-dir configs/three/

SEED0=$(jq -r '.secret' $GAIA_CONF/ibc0/n0/gaiacli/key_seed.json)
SEED1=$(jq -r '.secret' $GAIA_CONF/ibc1/n0/gaiacli/key_seed.json)
SEED2=$(jq -r '.secret' $GAIA_CONF/ibc2/n0/gaiacli/key_seed.json)
echo 
echo "Key $(rly keys restore ibc0 testkey "$SEED0") imported from ibc0 to relayer..."
echo "Key $(rly keys restore ibc1 testkey "$SEED1") imported from ibc1 to relayer..."
echo "Key $(rly keys restore ibc2 testkey "$SEED2") imported from ibc2 to relayer..."
echo
echo "Creating lite clients..."
echo
sleep 3
rly lite init ibc0 -f
rly lite init ibc1 -f
rly lite init ibc2 -f