#!/bin/bash
# this script called on each start of vstorage-target-monitor.service
# to switch qla2xxx kernel module in target mode

enable_qla2xxx_target_mode() {
	adapters_cnt=$(lspci | grep QLogic 2>/dev/null | wc -l)
	[ $adapters_cnt -eq 0 ] && return 0

	if [ -d "/sys/module/qla2xxx" ] ; then
			mode=$(cat /sys/module/qla2xxx/parameters/qlini_mode 2>/dev/null | sed "#s#\s#g")
			if [ "$mode" == "disabled" ] ; then
					# already in target mode
					return 0
			fi
			/usr/sbin/rmmod qla2xxx
			if [ $? -ne 0 ] ; then
					echo "Can't unload module qla2xxx" 1>&2
					return 1
			fi
	fi

	/usr/sbin/modprobe qla2xxx qlini_mode=disabled
	if [ $? -ne 0 ] ; then
			echo "Failed to load qla2xxx module in target mode" 1>&2
			return 1
	fi

	mode=$(cat /sys/module/qla2xxx/parameters/qlini_mode 2>/dev/null | sed "#s#\s#g")
	if [ "$mode" != "disabled" ] ; then
			echo "Can't switch qla2xxx module in target mode" 1>&2
			return 1
	fi
	return 0
}

if [ -f /etc/vstorage/iscsi/config.json ] ; then
	subsys=$(grep -v "^#" /etc/vstorage/iscsi/config.json 2>/dev/null | sed -e 's/[{" \t}]/''/g' | awk -v RS=',' -F : '/Subsystem/ { print $2 }')
	if [ "$subsys" = "TCM" ] ; then
		enable_qla2xxx_target_mode
	fi
fi


# always return zero !
exit 0

