#!/usr/bin/openrc-run

: ${RDMA_CONFIG:=${RDMA_CONFIG:-"/opt/etc/rdma.conf"}}

description="Executing rdma-init-kernel script."

. /opt/etc/functions.openrc

depend()
{
	use modules
	before net target mlx4mode
	provide ${SVCNAME}
}

start()
{
	local _rv=0 _nca _ca _np _p
	ebegin "Starting \"${SVCNAME}\""
	eindent
	update_me
	einfo "${ME}: loading InfiniBand kernel modules..."

	/usr/lib/rdma/rdma-init-kernel || _rv=1

	# FIXME: this step is propably needed only for QLogic cards
	_nca=`ibstat | grep '^CA ' | wc -l`
	if [ ${_nca} -eq 0 ]; then
		eerror "${ME}: no InfiniBand adapters found!"
		_rv=1
	else
		_can=0
		for _ca in `ibstat | grep '^CA ' | awk '{print $2;}' | sed "s/'//g"`; do
			_np=`ibstat ${_ca} | grep Port\ [0-9]:$ | wc -l`
			update_me
			if [ ${_np} -eq 0 ]; then
				eerror "${ME}: no ports found for HCA ${_ca}!"
				_rv=1
			else
				for _port in `seq 1 ${_np}`; do
					einfo "${ME}: enabling port ${_port} of HCA ${_ca} ..."
					ibportstate -D ${_can} ${_port} enable
				done
				# At leat one port is found
				_rv=0
			fi
			_can=$((${_can}+1))
		done
	fi
	eend ${_rv}
	return ${_rv}
}

stop()
{
	ebegin "Stopping service \"${SVCNAME}\""
	eend 0
	return 0
}
