#!/usr/bin/env bash
# =====================================================================
#  Verification suite for the Ansible/Proxmox VE workshop.
#
#  Usage (from the project root, e.g. ~/ansible-proxmox):
#     ./tests/run.sh 03                 # check one lab
#     ./tests/run.sh all                # check everything up to now
#     ./tests/run.sh 05 -vvv
#
#  Any extra arguments are passed through to ansible-playbook, so the
#  usual flags work:  --limit, -vvv, --check.
#
#  Exit code 0 = all checks passed.
# =====================================================================
set -uo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$HERE/.." && pwd)"
cd "$ROOT" || exit 2

WHICH="${1:-all}"
[ $# -gt 0 ] && shift

if [ "$WHICH" = "all" ]; then
  PLAYS=$(ls "$HERE"/verify-*.yml | sort)
else
  PLAYS="$HERE/verify-${WHICH}.yml"
  if [ ! -f "$PLAYS" ]; then
    echo "No check suite for '$WHICH'. Available:" >&2
    ls "$HERE"/verify-*.yml | sed 's#.*/verify-##; s#\.yml##' | tr '\n' ' ' >&2
    echo >&2
    exit 2
  fi
fi

pass=0; fail=0; failed_list=""

for play in $PLAYS; do
  label="$(basename "$play" .yml | sed 's/verify-/exercise /')"
  echo
  echo "=============================================================="
  echo "  $label"
  echo "=============================================================="
  # shellcheck disable=SC2068
  if ansible-playbook "$play" ${@:-}; then
    pass=$((pass + 1))
    echo "  -> PASS: $label"
  else
    fail=$((fail + 1))
    failed_list="$failed_list $label"
    echo "  -> FAIL: $label"
  fi
done

echo
echo "=============================================================="
printf '  result: %d passed, %d failed\n' "$pass" "$fail"
[ -n "$failed_list" ] && printf '  failed:%s\n' "$failed_list"
echo "=============================================================="

[ "$fail" -eq 0 ]
