#!/bin/sh

# PROVIDE: binmisc
# REQUIRE: LOGIN
# KEYWORD: shutdown

. /etc/rc.subr

name="binmisc"
desc="Load binmisc activators"
rcvar="binmisc_enable"
binmiscctl_program="/usr/sbin/binmiscctl"
start_cmd="binmisc_start"
stop_cmd="binmisc_stop"
status_cmd="binmisc_status"

# To enable 'status'
procname="${binmiscctl_program}"

binmisc_start() {
	local name magic size mask offset _i
	for name in ${binmisc_names}; do
		eval "magic=\"\${binmisc_${name}_magic}\""
		eval "size=\"\${binmisc_${name}_size}\""
		eval "mask=\"\${binmisc_${name}_mask}\""
		eval "interpreter=\"\${binmisc_${name}_interpreter}\""
		eval "offset=\"\${binmisc_${name}_offset:-0}\""
		if [ -z "${mask}" ]; then
			# It currently doesn't work without a '--mask'
			_i=0
			while [ ${_i} -lt ${size} ]; do
				mask="\\xff${mask}"
				_i=$((_i+1))
			done
		fi
		${binmiscctl_program} add ${name} --magic "${magic}" --size "${size}" --mask "${mask}" --interpreter "${interpreter}" --offset "${offset}" --set-enabled
	done
}

binmisc_stop() {
	for name in ${binmisc_names}; do
		${binmiscctl_program} remove ${name}
	done
	kldstat -q -n imgact_binmisc.ko && kldunload imgact_binmisc.ko
}

binmisc_status() {
	if ! kldstat -q -m imgact_binmisc; then
		echo "Kernel module imgact_binmisc not loaded" 1>&2
		return 1
	fi
	${binmiscctl_program} list
}


load_rc_config ${name}

: ${binmisc_enable="NO"}

run_rc_command "$1"
