#!/bin/ksh

set -eu

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

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

setprogname "robsd-clean"

_keep=
_mode=""

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

setmode "${_mode}"

case "${_mode}" in
canvas)
	[ -n "${ROBSDCONF:-}" ] || usage
	;;
*)
	[ "$(id -u)" -ne 0 ] && fatal "must be run as root"
	;;
esac

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

_keep="${1:-0}"
if [ "${_keep}" -eq 0 ]; then
	_keep="${KEEP}"
fi
if [ "${_keep}" -eq 0 ]; then
	exit 0
fi

if [ "$(config_value keep-attic)" -eq 1 ]; then
	purge "${ROBSDDIR}" "${_keep}" | while read -r _d; do
		info "moving ${_d} to ${KEEPDIR}"
	done
else
	purge -d "${ROBSDDIR}" "${_keep}" | while read -r _d; do
		info "removing ${_d}"
		rm -rf "${_d}"
	done
fi
