#!/bin/sh
set -eu

PRE15_LIB_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/lib" && pwd -P)
PRE15_BUILD_SCRIPT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)/run-build.sh
export PRE15_LIB_DIR PRE15_BUILD_SCRIPT
. "$PRE15_LIB_DIR/runner.sh"
. "$PRE15_LIB_DIR/manifest.sh"

pre15_build_worker()
{
	pre15_build_config=$1
	case "$pre15_build_config" in
	zstdio0) pre15_zstdio=0 ;;
	zstdio1) pre15_zstdio=1 ;;
	*) pre15_fail_usage "unknown build configuration: $pre15_build_config" ;;
	esac
	pre15_require_paths
	test "$(uname -s)" = FreeBSD || \
		pre15_infra_blocked 'run-build.sh requires a native FreeBSD build host'
	test -d "$PRE15_FREEBSD_SRC/sys" || \
		pre15_infra_blocked "FreeBSD source tree is absent: $PRE15_FREEBSD_SRC"
	pre15_write_argv_json "$PRE15_RUN_DIR/build-argv.json" \
		env "FREEBSD_SRC=$PRE15_FREEBSD_SRC" "WITH_ZSTDIO=$pre15_zstdio" \
		"$PRE15_DUT/build.sh"
	pre15_target_reached
	if env FREEBSD_SRC="$PRE15_FREEBSD_SRC" WITH_ZSTDIO="$pre15_zstdio" \
	    "$PRE15_DUT/build.sh"; then
		:
	else
		pre15_dut_fail "native FreeBSD build failed for $pre15_build_config"
	fi
	pre15_record_module "$PRE15_DUT/build/erofs.ko"
}

if test "${1:-}" = --worker; then
	shift
	test "$#" -eq 1 || pre15_fail_usage 'internal build worker requires one config'
	pre15_build_worker "$1"
	exit 0
fi

test "$#" -eq 1 || pre15_fail_usage 'usage: run-build.sh zstdio0|zstdio1'
case "$1" in
zstdio0|zstdio1) ;;
*) pre15_fail_usage "unknown build configuration: $1" ;;
esac
pre15_run_command build "$1" "${PRE15_BUILD_TIMEOUT:-1200}" \
	"$PRE15_BUILD_SCRIPT" --worker "$1"
