#!/bin/ksh

set -eu

usage() {
	echo "usage: robsd-rescue" 1>&2
	exit 1
}

# last_release
last_release() {
	find "$ROBSDDIR" -mindepth 1 -maxdepth 1 -type d |
	grep -v -e "$KEEPDIR" |
	sort -nr |
	head -1
}

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

[ $# -ne 0 ] && usage

# shellcheck disable=SC2034
DETACH=0

setmode -p "$0"
setprogname "${_MODE}-rescue"
[ "$(id -u)" -ne 0 ] && fatal "must be run as root"
config_load <<-'EOF'
ROBSDDIR="${robsddir}"
KEEPDIR="${keep-dir}"
EOF

BUILDDIR="$(last_release)"
if [ -z "$BUILDDIR" ]; then
	fatal "release directory not found"
else
	info "using release directory ${BUILDDIR}"
fi

lock_acquire "$ROBSDDIR" "$BUILDDIR"

if step_eval -n patch "$(step_path "$BUILDDIR")" 2>/dev/null; then
	step_exec -X -f "${BUILDDIR}/tmp/fail" -l /dev/null -s revert || :
else
	info "step patch not found, cannot revert diff(s)"
fi

if lock_release "$ROBSDDIR" "$BUILDDIR"; then
	info "released lock"
fi
