#!/bin/sh
# Swarmetry load test gate for any CI (Jenkins, Azure Pipelines, Bitbucket Pipelines, CircleCI, a cron job...).
# Served by your Swarmetry server, with its address written in:
#   https://swarmetry.io/cli/templates/swarmetry-ci.sh
# Guide: "Load tests in a CI pipeline" in the help centre (https://swarmetry.io/app/help/ci).
#
# 1. Downloads the swarmetry command line of this computer from your server and checks it: against the SHA-256 you
#    pinned (pinned_version and pinned_sha256 below, the secure choice), otherwise against SHA256SUMS of your server,
#    itself verified with Swarmetry's release key when one is written below.
# 2. Starts the test and waits for its verdict. -y confirms the start: a test sends load to your site and uses the
#    quotas of your plan, and a pipeline has no terminal to ask you. When the run policy of your organization requires a
#    passed preflight, the command line runs it first and starts the test with it (--preflight-if-required).
# 3. Writes the JUnit XML of the test for the test report of your CI, also when the test fails.
# 4. Exits 0 when the test passes, otherwise with the code of the command line (explained in the log).
#
# Set these variables in your CI. Keep the token in the secret store of your CI, never in a file of your repository.
#   SWARMETRY_TOKEN           (secret) token of a service account, sw_sat_..., Administration > Service accounts
#   SWARMETRY_PROJECT_ID      project of the test
#   SWARMETRY_SCENARIO_ID     scenario to run
#   SWARMETRY_TEST_CONFIG_ID  test configuration (load and thresholds). Recommended: the thresholds decide the verdict.
#                             The address of a test configuration in Swarmetry holds the three ids:
#                             /app/projects/<project>/scenarios/<scenario>/configs/<test configuration>
# Optional:
#   SWARMETRY_ENVIRONMENT_ID  environment of the project (base URL, variables)
#   SWARMETRY_TIMEOUT         longest wait, then the test is stopped (default 1h)
#   SWARMETRY_JUNIT           JUnit file (default swarmetry-junit.xml)
#   SWARMETRY_SUMMARY         summary file, JSON (default swarmetry-summary.json)
#   SWARMETRY_NOTE            note shown with the test in Swarmetry (default: CI)
#   SWARMETRY_ALLOW_INCONCLUSIVE=1  an inconclusive test passes with a warning (default: it fails the job)
#   SWARMETRY_ALLOW_NO_VERDICT=1    a test without thresholds passes (default: it fails the job)
#   SWARMETRY_INSTALL_DIR     folder of the command line (default .swarmetry/bin, reused while its checksum matches)
#   SWARMETRY_URL             your Swarmetry server (default: the address below; https only)
#
# Pinned command line (recommended): write below the version and the SHA-256 of the file of your CI machine (page
# Developer access of Swarmetry, or its line of SHA256SUMS), and commit this file. The job then runs only that file,
# whatever your server serves; after an upgrade of your server it stops and prints the new SHA-256 to check and pin.
#
# Run it with: sh swarmetry-ci.sh
# POSIX sh (dash, bash, BusyBox). Needs curl, sha256sum or shasum, and ssh-keygen (OpenSSH 8.1 or later) when a
# release key is written below. Linux and macOS. Downloads are https only, TLS 1.2 or later, never redirected to http.
# The token is read from the environment by the command line: this script never prints it.
# The whole script is the function main, called on its last line: a file cut short runs nothing.

main() {
	set -eu

	SWARMETRY_URL="${SWARMETRY_URL:-https://swarmetry.io}"
	# Pinned command line (the secure choice): the version and the SHA-256 of the file of your CI machine, for example
	# pinned_version='v4.0.0' and pinned_sha256='<64 hexadecimal characters>'. Empty: the file your server serves.
	pinned_version="${SWARMETRY_CLI_VERSION:-}"
	pinned_sha256="${SWARMETRY_CLI_SHA256:-}"
	# Swarmetry's release key, written in by your server (empty: none): SHA256SUMS is verified with it.
	release=''
	: "${SWARMETRY_TOKEN:?is not set: add the token of a service account as a secret variable of your CI}"
	: "${SWARMETRY_PROJECT_ID:?is not set: the id of the project of the test}"
	: "${SWARMETRY_SCENARIO_ID:?is not set: the id of the scenario to run}"
	export SWARMETRY_URL SWARMETRY_TOKEN
	timeout="${SWARMETRY_TIMEOUT:-1h}"
	junit="${SWARMETRY_JUNIT:-swarmetry-junit.xml}"
	summary="${SWARMETRY_SUMMARY:-swarmetry-summary.json}"
	bin="${SWARMETRY_INSTALL_DIR:-.swarmetry/bin}"

	say() { printf 'swarmetry-ci: %s\n' "$1" >&2; }
	fail() {
		say "$1"
		exit 1
	}

	# 1. The command line of this computer, from your server: the pinned file, or the file of SHA256SUMS (verified
	# with the release key when there is one).
	case "$(uname -s)" in
	Linux) os=linux ;;
	Darwin) os=darwin ;;
	*) fail "this script runs on Linux and macOS (this system is $(uname -s))" ;;
	esac
	case "$(uname -m)" in
	x86_64 | amd64) arch=amd64 ;;
	aarch64 | arm64) arch=arm64 ;;
	*) fail "no command line for the processor $(uname -m) (amd64 and arm64 only)" ;;
	esac
	name="swarmetry-$os-$arch"
	files="$SWARMETRY_URL/cli/files"
	# https only, TLS 1.2 or later, never a redirect to http (written in by your server; http only for a test server on this computer).
	proto='=https'
	case "$SWARMETRY_URL" in
	https://*) ;;
	*) [ "$proto" != '=https' ] || fail "SWARMETRY_URL must be an https address ($SWARMETRY_URL)" ;;
	esac
	command -v curl >/dev/null 2>&1 || fail "curl is needed to download the command line"
	fetch() { curl --proto "$proto" --proto-redir '=https' --tlsv1.2 -fsSL --retry 3 -o "$2" "$1"; }
	if command -v sha256sum >/dev/null 2>&1; then
		sha256() { sha256sum "$1" | cut -d ' ' -f 1; }
	elif command -v shasum >/dev/null 2>&1; then
		sha256() { shasum -a 256 "$1" | cut -d ' ' -f 1; }
	else
		fail "sha256sum or shasum is needed to check the download"
	fi
	mkdir -p "$bin"
	if [ -n "$pinned_version$pinned_sha256" ]; then
		[ -n "$pinned_version" ] && [ -n "$pinned_sha256" ] ||
			fail "pinned command line: set both SWARMETRY_CLI_VERSION and SWARMETRY_CLI_SHA256"
		sum=$(printf '%s' "$pinned_sha256" | tr 'A-F' 'a-f')
		how="pinned $pinned_version, SHA-256 verified"
	else
		fetch "$files/SHA256SUMS" "$bin/SHA256SUMS" || fail "cannot download $files/SHA256SUMS"
		how="checksum verified"
		if [ -n "$release" ]; then
			command -v ssh-keygen >/dev/null 2>&1 ||
				fail "ssh-keygen (OpenSSH 8.1 or later) is needed to verify the signature of SHA256SUMS: install the OpenSSH client"
			fetch "$files/SHA256SUMS.sig" "$bin/SHA256SUMS.sig" ||
				fail "cannot download $files/SHA256SUMS.sig: your server does not sign its checksums, nothing was run"
			printf '%s\n' "$release" >"$bin/allowed_signers"
			ssh-keygen -Y verify -f "$bin/allowed_signers" -I swarmetry-cli -n 'cli.swarmetry.io' \
				-s "$bin/SHA256SUMS.sig" <"$bin/SHA256SUMS" >/dev/null 2>&1 ||
				fail "the signature of SHA256SUMS does not verify with Swarmetry's release key: nothing was run"
			how="checksum and signature verified"
		fi
		sum=$(awk -v n="$name" '$2 == n { print $1 }' "$bin/SHA256SUMS")
		[ -n "$sum" ] || fail "$name is not listed in SHA256SUMS of $SWARMETRY_URL"
	fi
	if [ -x "$bin/swarmetry" ] && [ "$(sha256 "$bin/swarmetry")" = "$sum" ]; then
		say "command line already installed in $bin ($how)"
	else
		fetch "$files/$name" "$bin/$name" || fail "cannot download $files/$name"
		got=$(sha256 "$bin/$name")
		if [ "$got" != "$sum" ]; then
			rm -f "$bin/$name"
			[ -z "$pinned_sha256" ] ||
				fail "your server serves another command line than the one pinned here (SHA-256 $got, pinned $sum): nothing was run. If your server was upgraded, check the new file on the page Developer access, then update SWARMETRY_CLI_VERSION and SWARMETRY_CLI_SHA256"
			fail "the checksum of $name does not match SHA256SUMS: nothing was run (download again; if it fails again, contact Swarmetry support)"
		fi
		chmod 0755 "$bin/$name"
		mv -f "$bin/$name" "$bin/swarmetry"
		say "installed $("$bin/swarmetry" --version) in $bin ($how)"
	fi
	if [ -n "$pinned_version" ]; then
		got=$("$bin/swarmetry" --version)
		got=${got##* }
		[ "${got#v}" = "${pinned_version#v}" ] ||
			fail "the pinned file is version $got, not $pinned_version: correct SWARMETRY_CLI_VERSION or SWARMETRY_CLI_SHA256"
	fi

	# 2. Start the test and wait for its verdict.
	set -- run start --project-id "$SWARMETRY_PROJECT_ID" --scenario-id "$SWARMETRY_SCENARIO_ID"
	if [ -n "${SWARMETRY_TEST_CONFIG_ID:-}" ]; then set -- "$@" --test-config-id "$SWARMETRY_TEST_CONFIG_ID"; fi
	if [ -n "${SWARMETRY_ENVIRONMENT_ID:-}" ]; then set -- "$@" --environment-id "$SWARMETRY_ENVIRONMENT_ID"; fi
	if [ "${SWARMETRY_ALLOW_NO_VERDICT:-0}" = 1 ]; then set -- "$@" --allow-no-verdict; fi
	# A required preflight (run.preflight_required) is run first, then the test starts with it; exit 26 when it fails.
	set -- "$@" --note "${SWARMETRY_NOTE:-CI}" --preflight-if-required
	set -- "$@" -y --wait --timeout "$timeout" --stop-on-timeout --junit "$junit" --summary-json "$summary"

	# A cancelled job stops the test it started: the CI signals this shell, which passes the signal on to the command
	# line (it stops the test, then exits 130).
	"$bin/swarmetry" "$@" &
	pid=$!
	trap 'kill -TERM "$pid" 2>/dev/null || :' INT TERM
	code=0
	wait "$pid" || code=$?
	while kill -0 "$pid" 2>/dev/null; do
		code=0
		wait "$pid" || code=$?
	done
	trap - INT TERM

	# 3. What the exit code means for this pipeline.
	case "$code" in
	0) say "the test passed" ;;
	20) say "the test failed: a threshold failed, or the test was stopped by a threshold (see the summary above)" ;;
	21)
		if [ "${SWARMETRY_ALLOW_INCONCLUSIVE:-0}" = 1 ]; then
			say "warning: the test is inconclusive (reasons above); SWARMETRY_ALLOW_INCONCLUSIVE=1 lets the job pass"
			exit 0
		fi
		say "the test is inconclusive: nothing failed, but it cannot be declared passed (reasons above). SWARMETRY_ALLOW_INCONCLUSIVE=1 lets it pass"
		;;
	22) say "the test has no threshold, so no verdict: add thresholds to its test configuration, or set SWARMETRY_ALLOW_NO_VERDICT=1" ;;
	23) say "the test was stopped before its end, by a person, an emergency stop or a limit (see the summary above)" ;;
	24) say "technical failure of the test (error code above): run the job again; if it fails again, tell your administrator" ;;
	25) say "the test was still running after $timeout and was stopped: raise SWARMETRY_TIMEOUT or shorten the test" ;;
	26) say "the preflight the run policy requires did not pass (findings above), so the test was not started: fix the scenario, then run the job again" ;;
	3) say "the token was refused or has expired: create a token of the service account and update the secret of your CI" ;;
	4) say "the start was refused (error code and hint above): a permission of the service account, your plan, an address that is not an allowed target, or your organization's allowed IP ranges. Do not retry in a loop" ;;
	6) say "the start was refused by a rule of your organization (error code and hint above): an approval is required (Administration > Approvals), or the required preflight could not be used. Do not retry in a loop" ;;
	7) say "the test cannot start as configured (error code and hint above): check the ids, the test configuration, its secrets and datasets" ;;
	8) say "a quota or a limit of your plan is reached, or too many requests (error code above). Do not retry in a loop" ;;
	11) say "the server cannot be reached: check SWARMETRY_URL and the network of this runner" ;;
	130) say "interrupted: the test this job started was stopped" ;;
	*) say "the command line exited with code $code (see the exit codes in the guide)" ;;
	esac
	exit "$code"
}

main "$@"
