#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."

socket_path="${UCE_CLI_SOCKET:-/run/uce/cli.sock}"
if [[ -z "${UCE_CLI_SOCKET:-}" && -r /etc/uce/settings.cfg ]]; then
	configured_socket=$(awk -F= '/^[[:space:]]*CLI_SOCKET_PATH[[:space:]]*=/ {gsub(/^[[:space:]]+|[[:space:]]+$/, "", $2); print $2; exit}' /etc/uce/settings.cfg)
	if [[ -n "${configured_socket:-}" ]]; then
		socket_path="$configured_socket"
	fi
fi

include_kill=0
action="run"
while [[ $# -gt 0 ]]; do
	case "$1" in
		--include-wasm-kill|--include-kill)
			include_kill=1
			shift
			;;
		--list)
			action="list"
			shift
			;;
		-h|--help)
			cat <<'USAGE'
Usage: scripts/run_cli_tests.sh [--include-wasm-kill] [--list]

Runs the UCE unit-based test suite through the runtime CLI socket.
USAGE
			exit 0
			;;
		*)
			echo "unknown option: $1" >&2
			exit 2
			;;
	esac
done

if [[ ! -S "$socket_path" ]]; then
	echo "UCE CLI socket not found: $socket_path" >&2
	exit 1
fi

url="http://localhost/tests/cli_runner.uce?action=${action}&include_kill=${include_kill}"
exec curl -sS --fail-with-body --unix-socket "$socket_path" "$url"
