#!/bin/ksh

set -eu

usage() {
	xargs 1>&2 <<-EOF
	usage: robsd-regress
	[-d]
	[-S src-diff]
	[-c comment]
	[-r path]
	[-s step]
	[-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}"
SKIP="${skip}"
STATINTERVAL="${stat-interval}"
BSDDIFF="${bsd-diff}"
BSDSRCDIR="${bsd-srcdir}"
REGRESSUSER="${regress-user}"
EOF

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

while getopts "dS:c:r:s:t:" opt; do
	case "${opt}" in
	d)	DETACH=0;;
	S)	BSDDIFF="${BSDDIFF} $(readlink -f "${OPTARG}")";;
	c)	_comment="${OPTARG}";;
	r)	BUILDDIR="$(readlink -f "${OPTARG}")";;
	s)	SKIP="${SKIP}${SKIP:+ }${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}" >"$(config_value comment-path)"
	elif [ -n "${BSDDIFF}" ]; then
		# Generate comment including a list of the diff(s).
		{
			echo 'Applied the following diff(s):'
			echo "${BSDDIFF}" | xargs ls
		} >"$(config_value comment-path)"
	fi

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

	if [ -n "${SKIP}" ]; then
		info "skipping steps: ${SKIP}"
		for _skip in ${SKIP}; do
			_id="$(step_id "${_skip}")"
			step_write -S -t -s "${_id}" -n "${_skip}" -e 0 -d 0 -l "" \
				"$(step_path "${BUILDDIR}")"
		done
	fi

	if [ -n "${_tags}" ]; then
		echo "${_tags}" >"$(config_value tags-path)"
	fi

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

"${ROBSDCLEAN}" -m "${_MODE}" ${ROBSDCONF:+"-C${ROBSDCONF}"}

"${ROBSDSTAT}" -i "${STATINTERVAL}" -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
