#!/usr/bin/env bash

# Running this script with no parameters will build docker image for indypool with hostname: indyscanpool
# If you want to build the pool for different url instead of "indyscanpool", for exaple "localhost", you can do so
# by setting environment variable "POOL_ADDRESS"  to desired value, prior to executing the script.
# Example: POOL_ADDRESS=localhost ./build-pool.sh

REPO_OWNER="hyperledger"
INDY_VERSION="v1.15.0"
TMP_INDYSDK=/tmp/indyscan-indysdk

DOCKER_BUILD_PARAMS="$1"

if [ ! -d "$TMP_INDYSDK" ]; then
    git clone "https://github.com/${REPO_OWNER}/indy-sdk.git" "$TMP_INDYSDK"
fi;

(cd "$TMP_INDYSDK" && git checkout -- . && git fetch && git checkout "$INDY_VERSION")
if [ $? -ne 0 ]; then
    echo "Could not checkout indy-sdk at revision $INDY_VERSION";
    exit 1;
fi;

if [ -z "$POOL_ADDRESS" ]; then
  POOL_ADDRESS="indyscanpool"
  echo "Using default POOL_ADDRESS=${POOL_ADDRESS}"
fi

if [ -z "$INDYPOOL_IMAGE_TAG" ]; then
  INDYPOOL_IMAGE_TAG="indypool:$POOL_ADDRESS-$INDY_VERSION"
  echo "Using autogenerated INDYPOOL_IMAGE_TAG=${INDYPOOL_IMAGE_TAG}"
fi

echo "This will build ${INDYPOOL_IMAGE_TAG}"
echo "Do you want to continue? (y/n)"
read yesno
if [ $yesno != "y" ]; then
  exit 0
fi
echo "Building image!"

cd "$TMP_INDYSDK" || exit 1
docker build ${DOCKER_BUILD_PARAMS} --build-arg pool_ip="$POOL_ADDRESS" -f "ci/indy-pool.dockerfile" -t "$INDYPOOL_IMAGE_TAG" .

echo "Image built"
docker image ls "$INDYPOOL_IMAGE_TAG"

echo "Indy Network genesis for this image:"
docker run "$INDYPOOL_IMAGE_TAG" cat /var/lib/indy/sandbox/pool_transactions_genesis
