#!/bin/ksh

set -eu

usage() {
	xargs 1>&2 <<-EOF
	usage: robsd-ports
	[-d]
	[-P ports-patch]
	[-c comment]
	[-r path]
	[-s step]
	[-t tag]
	[pkgpath ...]
	EOF
	exit 1
}

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

setmode "robsd-ports"
setprogname "robsd-ports"
[ "$(id -u)" -ne 0 ] && fatal "must be run as root"

config_load <<'EOF'
ROBSDDIR="${robsddir}"
CHROOT="${chroot}"
KEEP="${keep}"
SKIP="${skip}"
STATINTERVAL="${stat-interval}"
PORTS="${ports}"
PORTSDIFF="${ports-diff}"
PORTSDIR="${ports-dir}"
EOF

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

while getopts "dP:c:r:s:t:" opt; do
	case "$opt" in
	d)	DETACH=0;;
	P)	PORTSDIFF="${PORTSDIFF} $(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))
if [ $# -gt 0 ]; then
	PORTS="$*"
	SKIP="${SKIP}${SKIP:+ }cvs clean proot distrib"
fi

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 "$PORTSDIFF" ]; then
		# Generate comment including a list of the diff(s).
		{
			echo 'Applied the following diff(s):'
			echo "$PORTSDIFF" | xargs ls
		} >"${BUILDDIR}/comment"
	fi

	# shellcheck disable=SC2086,SC2153
	diff_copy -d "${CHROOT}${PORTSDIR}" "${BUILDDIR}/ports.diff" $PORTSDIFF

	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" >"${BUILDDIR}/tags"
	fi

	# List of ports used by the steps.
	echo "$PORTS" | xargs printf '%s\n' >"${BUILDDIR}/tmp/ports"

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

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

"$ROBSDSTAT" -i "$STATINTERVAL" -u _pbuild -u _pfetch >>"${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
