#!/usr/bin/openrc-run

description="Infiniband subnet management"

. /opt/etc/functions.openrc

IB_ALL_PORTS=${IB_ALL_PORTS-"NO"}

PIDFILE="/var/run/opensmd.pid"
MONITOR="/opt/bin/autorestart"

depend()
{
	before libvirtd
	provide ${SVCNAME}
}

start()
{
	local _rc=1
	ebegin "Starting \"${SVCNAME}\""
	if [ "${IB_ALL_PORTS}" = "YES" ]; then
		local _guid _mode
		GUIDS=`ibstat -p`
		if [ $? -ne 0 ]; then
			eend 1
			return 1
		fi
		# Assume success if _at least one_ SM is started
		for _guid in ${GUIDS}; do
			# Determine port mode
			_mode=`ibstat | grep --after-context 1 ${_guid} | tail -n 1 | sed 's/.*layer: //g'`
			if [ "${_mode}" != "InfiniBand" ]; then
				update_me
				ewarn "${ME}: port ${_guid} in ${_mode} mode, skipping"
				continue
			fi
			PIDFILE="/var/run/opensmd-${_guid}.pid"
			# FIXME: should I use separate log files?
			# This is quite simple: --log-file /var/log/opensm-${_guid}.log
			# As of opensm 3.3.19, output to common log file is just Ok.
			start-stop-daemon --background --pidfile ${PIDFILE} --make-pidfile \
				--start --exec ${MONITOR} -- /sbin/opensm 1 1 --- -g ${_guid}
			[ $? -eq 0 ] && _rc=0
		done
	else
		start-stop-daemon --background --pidfile ${PIDFILE} --make-pidfile \
			--start --exec ${MONITOR} -- /sbin/opensm 1 1
		_rc=$?
	fi
	eend ${_rc}
	return ${_rc}
}

stop()
{
	ebegin "Stopping service \"${SVCNAME}\""
	if [ "${IB_ALL_PORTS}" = "YES" ]; then
		local _guid
		for _guid in `ibstat -p`; do
			PIDFILE="/var/run/opensmd-${_guid}.pid"
			start-stop-daemon --stop --exec ${MONITOR} --retry SIGTERM/5 --pidfile ${PIDFILE}
		done
	else
		start-stop-daemon --stop --exec ${MONITOR} --retry SIGTERM/5 --pidfile ${PIDFILE}
	fi
	eend 0
	return 0
}
