#!/bin/ksh

set -eu

usage() {
	xargs 1>&2 <<-EOF
	usage: robsd-regress
	[-d]
	[-S src-diff]
	[-c comment]
	[-r path]
	[-t tag]
	EOF
	exit 1
}

. "${EXECDIR:-/usr/local/libexec/robsd}/util.sh"
. "${EXECDIR:-/usr/local/libexec/robsd}/util-regress.sh"

setmode "robsd-regress"
setprogname "robsd-regress"
[ "$(id -u)" -ne 0 ] && fatal "must be run as root"
config_load <<'EOF'
ROBSDDIR="${robsddir}"
KEEP="${keep}"
BSDDIFF="${bsd-diff}"
BSDSRCDIR="${bsd-srcdir}"
REGRESSUSER="${regress-user}"
EOF

_comment=""
_statpid=""
_step=1
_tags=""

while getopts "dS:c:r:t:" opt; do
	case "$opt" in
	d)	DETACH=0;;
	S)	BSDDIFF="${BSDDIFF} $(readlink -f "${OPTARG}")";;
	c)	_comment="$OPTARG";;
	r)	BUILDDIR="$(readlink -f "$OPTARG")";;
	t)	_tags="${_tags}${_tags:+ }${OPTARG}";;
	*)	usage;;
	esac
done
shift $((OPTIND - 1))
[ $# -ne 0 ] && usage

trap 'trap_exit -r "$ROBSDDIR" -b "$BUILDDIR" -s "$_statpid"' EXIT

if [ -z "$BUILDDIR" ]; then
	check_perf
	BUILDDIR="${ROBSDDIR}/$(build_id "$ROBSDDIR")"
else
	_step="$(step_next "$(step_path "$BUILDDIR")")"
fi
build_init "$BUILDDIR"
info "using directory ${BUILDDIR} at step ${_step}"

lock_acquire "$ROBSDDIR" "$BUILDDIR"

if [ "$_step" -eq 1 ]; then
	if [ -n "$_comment" ]; then
		cat "$_comment" >"${BUILDDIR}/comment"
	elif [ -n "$BSDDIFF" ]; then
		# Generate comment including a list of the diff(s).
		{
			echo 'Applied the following diff(s):'
			echo "$BSDDIFF" | xargs ls
		} >"${BUILDDIR}/comment"
	fi

	# shellcheck disable=SC2086
	diff_copy -d "$BSDSRCDIR" "${BUILDDIR}/src.diff" $BSDDIFF

	if [ -n "$_tags" ]; then
		echo "$_tags" >"${BUILDDIR}/tags"
	fi

	"$ROBSDSTAT" -H >"${BUILDDIR}/stat.csv"
fi

if [ "$KEEP" -gt 0 ]; then
	/usr/local/sbin/robsd-regress-clean "$KEEP"
fi

"$ROBSDSTAT" -u "$REGRESSUSER" -u root >>"${BUILDDIR}/stat.csv" 2>&1 &
_statpid="$!"

if [ "$DETACH" -eq 1 ]; then
	# Signal to info() that no further output should be written to robsd.log
	# as we're about redirect all output to the same log.
	DETACH=2
	exec </dev/null >>"${BUILDDIR}/robsd.log" 2>&1

	# Reinstall trap handler since they are not inherited by subprocesses.
	trap '-' EXIT
	{
		trap 'trap_exit -r "$ROBSDDIR" -b "$BUILDDIR" -s "${_statpid}"' EXIT
		robsd -b "$BUILDDIR" -s "$_step"
	} &
	info "running in detach mode as pid ${!}"
else
	info "running as pid ${$}"
	robsd -b "$BUILDDIR" -s "$_step"
fi
