#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done
SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

VMLIST="centos7
ubuntu2004"

readonly CMD_SYSTEMTEST="./ci_test.sh systemtest.toml"
readonly CMD_PACKAGING="./pkg_build.sh nightly noupload"

usage()
{
  echo "./test_installer.sh [systemtest|packaging|custom cmd]"
  echo ""
  echo "If no argument is specified, 'systemtest' is assumed."
  echo ""
  echo "The following VMs are tested: $VMLIST"
  exit 0
}

process_args()
{
  cmd="$CMD_SYSTEMTEST"
  if [ -n "$1" ]; then
    case "$1" in
      -h|--help)  usage;;
      systemtest) cmd="$CMD_SYSTEMTEST";;
      packaging)  cmd="$CMD_PACKAGING";;
      *)          cmd="$@";;
    esac
  fi
}

process_cmd_in_parallel()
{
  echo "$VMLIST" | parallel --no-notice "$SCRIPT_DIR"/run_vm.sh {} {%} "$cmd"
}

process_result()
{
  local -r res=$1
  local -r vmnr=$(echo "$VMLIST" | wc -l)
  if [ "$res" -ne 0 ]; then
    echo "the installer test FAILED on $res out of $vmnr VMs."
  else
    echo "the installer test PASSED on all $vmnr VMs."
  fi
  echo "done."
}

type parallel > /dev/null 2>&1 || \
  { echo "this script requires GNU parallel to be installed and on the PATH."; exit 1; }

process_args "$@"
process_cmd_in_parallel
rc=$?
process_result $rc
exit $rc
