#!/bin/sh
# SPDX-License-Identifier: MIT

error() {
	printf "%s\n" "$@" >&2
	exit 1
}

fail() {
	local rc=$?
	printf "%s\n" "$@" >&2
	FAIL=1
	return $rc
}

skip() {
	printf "Skipping %s: " "$arg" >&2
	printf "%s\n" "$@" >&2
	# not a failure, terminate test as success
	exit 0
}

retry() {
	local i=0
	while [ "$i" -lt 10 ]; do
		"$@" && return
		sleep 1
		i=$((i+1))
	done
	return 1
}

check_req() {
	local tag="$1" expected="$2"
	[ "$(cat req)" = "$expected" ] \
		|| error "$tag: response did not contain: '$expected'"
}

check_req_jq() {
	# extra arguments after expected output are jq options e.g. -r -s
	local tag="$1" filter="$2" expected="$3"
	shift 3
	[ "$#" = 0 ] && set -- -r
	# shellcheck disable=SC2086 ## not quoting jqopt on purpose
	[ "$(jq "$@" "$filter" < req)" = "$expected" ] \
		|| error "$tag: response '$filter' did not contain '$expected'"
}

req() {
	local url="$1"
	shift
	rm -f req
	curl -o req -k -s --fail-with-body "$@" "$ABOSWEB_BASE/${url#/}"
}

req_bearer() {
	local url="$1"
	shift

	[ -e "token" ] \
		|| error "No token stored, did 00_create run first?"
	req "$url" -H "Authorization: Bearer $(cat token)" "$@"
}

req_json() {
	local url="$1"
	shift

	req_bearer "$url" -H "Content-type: application/json" "$@"
}

run_tests() {
	local FAIL=""
	for arg; do
		(
			set -e;
			"$arg"
		)
		# shellcheck disable=SC2181 ## `foo || fail` disables set -e,
		# so check exit code afterwards...
		if ! [ $? = 0 ]; then
			fail "$arg failed"
			if [ -e "req" ]; then
				echo "----------"
				# (awk adds missing new line at end of file if needed)
				awk 1 req
				echo "----------"
			fi
		fi
	done
	[ -z "$FAIL" ]
}

ssh_armadillo() {
	# shellcheck disable=SC2029 ## don't care about escaping client-side
	ssh ${ABOSWEB_SSH_CONFIG:+-F "$ABOSWEB_SSH_CONFIG"} armadillo "$@"
}

if [ "$#" = 2 ]; then
        ABOSWEB_BASE="https://$1:58080"
	# shellcheck disable=SC2034 ## used in 00_create.sh
        ABOSWEB_PASSWORD="$2"
elif [ "$#" = 1 ] && [ -e "$1" ]; then
        . "$(realpath "$1")"
elif [ "$#" = 1 ]; then
        ABOSWEB_BASE="https://$1:58080"
fi
# shellcheck disable=SC2034 ## used in swu.sh
TESTDIR="$(realpath "$(dirname "$0")/..")"

[ -n "$ABOSWEB_BASE" ] \
	|| error "ABOSWEB_BASE must be set (or given in parameter)"
