#!/bin/ksh

set -eu

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

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

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

_mode=""

while getopts "m:" opt; do
	case "${opt}" in
	m)	_mode="${OPTARG}";;
	*)	usage;;
	esac
done
shift $((OPTIND - 1))
{ [ -n "${_mode}" ] && [ $# -eq 0 ]; } || usage

setmode "${_mode}"

config_load <<-'EOF'
ROBSDDIR="${robsddir}"
KEEPDIR="${keep-dir}"
EOF

# shellcheck disable=SC2034
DETACH=0

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

lock_acquire "${ROBSDDIR}" "${BUILDDIR}"

if step_eval -n patch "$(step_path "${BUILDDIR}")" 2>/dev/null; then
	step_exec -X -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
