#! /usr/bin/env bash

set -e

function usage()
{
    echo -e "\t ================== script/cibuild-acceptance usage =================="
    echo -e "\t-h --help               : displays help message"
    echo -e "\t-l --local              : run locally without docker"
}

while [ "$1" != "" ]; do
    PARAM=`echo $1 | awk -F= '{print $1}'`
    VALUE=`echo $1 | awk -F= '{print $2}'`
    case $PARAM in
      -h | --help)
        usage
        exit
        ;;
      -l | --local)
        run_local=1
        ;;
      *)
      echo "ERROR: unknown parameter \"$PARAM\""
      usage
      exit 1
      ;;
    esac
    shift
done

# Get the repo dir
export REPO_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd )"
cd $REPO_DIR

TMPDIR=${REPO_DIR}/tmp
[ ! -d ${TMPDIR} ] && mkdir ${TMPDIR}
TMPFILE=$(mktemp ${TMPDIR}/octosecrets-acceptance.XXXXXX)

DOCKERFILE=${REPO_DIR}/spec/acceptance/docker-compose.yml

# determine if we have 'docker-compose' or 'docker compose'
if command -v docker-compose > /dev/null; then
  DOCKER_COMPOSE=docker-compose
elif command -v docker > /dev/null; then
  DOCKER_COMPOSE="docker compose"
else
  echo "ERROR: neither docker-compose or docker not found"
  exit 1
fi

function kill_containers {
  echo "Stopping docker containers"
  cd $REPO_DIR && $DOCKER_COMPOSE -f ${DOCKERFILE} down --remove-orphans
  sleep 2
}


function stop_vault_container {
  echo "Stopping vault container"
  cd $REPO_DIR && $DOCKER_COMPOSE -f ${DOCKERFILE} stop vault
  sleep 2
  echo "Stopped vault"
}


# For local, we only want to shut down if testing completed for all vault versions
completed=1

function cleanup {
  rv=$?
  echo "%%%FOLD {cleanup}%%%"
  if [[ -z $run_local ]]; then
    [ -f $TMPFILE ] && rm -f $TMPFILE
    echo "Stopping containers"
    kill_containers
  else
    if [ $completed -ne 0 ]; then
      echo "Leaving vault container running for debugging"
      echo "VAULT_ADDR=${VAULT_ADDR}"
      echo "VAULT_TOKEN=${VAULT_TOKEN}"
    fi
  fi

  if [ ! -f "/.github-full-larger-runner" ]; then
      rm -f "${WORKSPACE}/apt-auth-conf ${WORKSPACE}/pkg-mirror-host"
  fi
  echo "%%%END FOLD%%%"
}

trap cleanup EXIT

if [ ! -f "/.github-full-larger-runner" ]; then
    WORKSPACE=$REPO_DIR
    touch -r ${WORKSPACE}/Dockerfile ${WORKSPACE}/apt-auth-conf ${WORKSPACE}/pkg-mirror-host
fi


function wait_for_vault {
  echo "Leaving vault container running for debugging.  Connection details:"
  echo "VAULT_ADDR=${VAULT_ADDR}"
  echo "VAULT_TOKEN=${VAULT_TOKEN}"
  read -p "Vault version '${vault_version}' is running for debugging.  Press 'enter' when finished to continue..."
}

echo "%%%FOLD {Starting mysql server}%%%"
$DOCKER_COMPOSE -f ${DOCKERFILE} build mysql-server
$DOCKER_COMPOSE -f ${DOCKERFILE} up --force-recreate -d mysql-server && retcode=$? || retcode=$?
if [ $retcode -ne 0 ]; then
  echo "Error starting mysql container."
  exit 1
fi

echo "%%%FOLD {Building Docker Container}%%%"
echo "Running 'docker build'"
$DOCKER_COMPOSE -f ${DOCKERFILE} build acceptance
echo "%%%END FOLD%%%"


echo "%%%END FOLD%%%"

echo "%%%FOLD {Starting github server}%%%"
$DOCKER_COMPOSE -f ${DOCKERFILE} up --build --force-recreate -d git-server && retcode=$? || retcode=$?
if [ $retcode -ne 0 ]; then
  echo "Error starting git-server container."
  exit 1
fi
echo "%%%END FOLD%%%"


# Start the vault container for each version of vault we want to test
vault_versions=(1.17.2 1.19)
for vault_version in "${vault_versions[@]}"; do
  export VAULT_VERSION=$vault_version
  echo "%%%FOLD {Starting Vault Docker Container for version ${version}}%%%"
  $DOCKER_COMPOSE -f ${DOCKERFILE} up --build --force-recreate -d vault && retcode=$? || retcode=$?
  if [ $retcode -ne 0 ]; then
    echo "Error starting vault container."
    exit 1
  fi
  echo "%%%END FOLD%%%"

  VAULT_ADDR="http://127.0.0.1:8300"
  VAULT_TOKEN="toor"

  echo "%%%END FOLD%%%"

  if [[ -z $run_local ]]; then
    echo "%%%FOLD {Running tests}%%%"
    VAULT_ADDR="http://vault.fake:8300"
    DATABASE_HOST="mysql.fake"
    OCTOKIT_API_ENDPOINT="http://github.fake:8080"
    $DOCKER_COMPOSE -f ${DOCKERFILE} run -e VAULT_ADDR=$VAULT_ADDR -e VAULT_TOKEN=$VAULT_TOKEN -e DATABASE_HOST=$DATABASE_HOST -e OCTOKIT_API_ENDPOINT=$OCTOKIT_API_ENDPOINT acceptance bash -c "script/test-acceptance" && retcode=$? || retcode=$?

    if [ $retcode -ne 0 ]; then
      echo "Error running tests"
      exit $retcode
    fi
    echo "%%%END FOLD%%%"
  else
    # Allows running locally against the docker compose vault.  leaves vault running for debugging after tests run against each version of vault.
    echo "VAULT_ADDR=${VAULT_ADDR}"
    echo "VAULT_TOKEN=${VAULT_TOKEN}"
    VAULT_TOKEN=$VAULT_TOKEN VAULT_ADDR=$VAULT_ADDR DATABASE_HOST="127.0.0.1" OCTOKIT_API_ENDPOINT="http://127.0.0.1:8080" script/test-acceptance -l && retcode=$? || retcode=$?

    # when running locally, leave vault running until user hits return
    echo
    wait_for_vault
  fi

  stop_vault_container
done

kill_containers

completed=0

# We're done!
echo ""
echo "*****************************************************************"
echo "cibuild-octosecrets-acceptance complete:"
echo "exit status = ${retcode}"
echo "*****************************************************************"
echo ""

exit $retcode
