#!/bin/bash
#==============================================================================
# Copyright and license info is available in the LICENSE file included with
# the Server Deployment Package (SDP), and also available online:
# https://swarm.workshop.perforce.com/projects/perforce_software-hms/view/main/LICENSE
#------------------------------------------------------------------------------

set -u

#==============================================================================
# Functions
function msg () { echo -e "$*"; }
function errmsg () { msg "\\nError: ${1:-Unknown Error}\\n"; ErrorCount+=1; }
function bail () { errmsg "${1:-Unknown Error}"; exit "${2:-1}"; }

#==============================================================================
# Declarations and Environment

declare -i ErrorCount=0
declare SDPEnvFile=
declare HMSTestEnvFile="$PWD/env.sh"
declare ThisScript="${0##*/}"
declare Version=1.1.2
declare ThisUser=

ThisUser=$(whoami)

msg "\\nStarting $ThisScript v$Version as $ThisUser@${HOSTNAME%%.*} on $(date)."

[[ ${BASH_VERSINFO[0]} -lt 4 ]] && \
   bail "${0##*/} requires bash version 4.x+; current bash version is $BASH_VERSION."

[[ -r "$HMSTestEnvFile" ]] || bail "Missing HMS test environment file: $HMSTestEnvFile"
source "$HMSTestEnvFile" ||\
   errmsg "Failed to load SDP environment file: $HMSTestEnvFile"

SDPEnvFile="${SDP_ENV:-/p4/common/bin/p4_vars}"

[[ -r "$SDPEnvFile" ]] || bail "Missing SDP environment file: $SDPEnvFile"
source "$SDPEnvFile" hms ||\
   errmsg "Failed to load HMS test environment file: $HMSTestEnvFile"

# Override P4TMP to work outside full SDP runtime environment.
export P4TMP="/tmp/hms.test"
[[ -d "$P4TMP" ]] || mkdir -p "$P4TMP"

declare BASH_LIBS=$P4U_ENV
BASH_LIBS+=" ${HMS_LIB}/hms_exe_versions.sh"

for bash_lib in $BASH_LIBS; do
   # shellcheck disable=SC1090
   source "$bash_lib" ||\
      errmsg "Failed to load bash lib [$bash_lib]. Aborting."
done

[[ "$ErrorCount" -eq 0 ]] || bail "Aborting due to lib load failures."

msg "Starting tests."
VERBOSITY=6

load_exe_versions 1
