#!/sbin/openrc-run

name="tgt-admin"
extra_started_commands="reload forcereload forcestop"

: "${tgtd_config:=/etc/tgt/targets.conf}"
required_files="${tgtd_config}"

depend() {
	need tgtd
}

start_pre() {
	# Put tgtd into "offline" state until all the targets are configured.
	tgtadm --op update --mode sys --name State -v offline
	retval=$?
	if [ $retval -eq 107 ]; then
		eerror "tgtd is not running"
		exit 1
	fi
}
start() {
	ebegin "Configuring targets"
	tgt-admin -e -c "${tgtd_config}"
	retval=$?
	if [ $retval -ne 0 ]; then
		eend $retval "Could not load configuration"
		exit 1
	fi
	tgt-admin --ready ALL
	tgtadm --op update --mode sys --name State -v ready
	eend $?
}

stop() {
	ebegin "Stopping ${SVCNAME}"
	if [ "$RC_RUNLEVEL" = "shutdown" ]; then
		# If we are shutting down, forcebly stop all targets.
		forcestop
	else
		tgtadm --op update --mode sys --name State -v offline >/dev/null 2>&1
		tgt-admin --offline ALL
		tgt-admin --update ALL -c /dev/null
		retval=$?
	fi
	eend $retval
}

forcestop() {
	ewarn "Forcefully clearing all targets before shutting down"
	tgtadm --op update --mode sys --name State -v offline >/dev/null 2>&1
	tgt-admin --offline ALL -f
	tgt-admin --update ALL -c /dev/null -f
	eend $?
}

reload() {
	ebegin "Reloading target configuration"
	tgt-admin --update ALL -c "$tgtd_config"
	eend $?
}

forcereload() {
	# Update configuration for targets, even those in use.
	# This could lead to data loss!
	ewarn "WARNING: Forcefully reloading target configuration"
	tgt-admin --update ALL -f -c "$tgtd_config"
	eend $?
}

status_post() {
	einfo "Run 'tgt-admin -s' for target info."
}
