#!/bin/bash
#
# (C) Copyright International Business Machines Corp., 2011-2025
#	lin_tape: Device Driver for IBM Tape Storage
#	This script loads/unloads the module and manages the
#       daemon associated with the driver
#

start() {
    echo -n -e "Starting lin_tape... \n"
	modprobe pfo
	RETVAL=$?
	[ $RETVAL -eq 0 ] && modprobe lin_tape
	RETVAL=$RETVAL||$?
	SFMP=0
	UBUNTU=0
	[ $RETVAL -eq 0 ]  &&
	[ -f /sys/module/lin_tape/parameters/lin_tape_as_sfmp ] &&
	SFMP=$(cat /sys/module/lin_tape/parameters/lin_tape_as_sfmp)
	if [[ $SFMP -eq 1 ]] && [ -x /usr/bin/lin_taped ]; then
	    echo -n -e "lin_tape as SFMP unloading st/sg to load stmp/sgmp\n"
	    UBUNTU=$(test -e /etc/os-release && grep -qi Ubuntu /etc/os-release && echo 1 || echo 0)
	    [ $UBUNTU -eq 0 ] && [ -d /sys/module/sg ] && rmmod sg
		[ -d /sys/module/st ] && rmmod st
		[ -d /sys/module/ch ] && rmmod ch
	    [ $UBUNTU -eq 0 ] && modprobe sgmp
	RETVAL=$?
	[ $RETVAL -ne 0 ] && echo -n -e "As lin_tape_as_sfmp is enabled build using -with sfmp\n"
		modprobe stmp
	fi
	[ $RETVAL -eq 0 ] && [ -x /usr/bin/lin_taped ] && /usr/bin/lin_taped start
	RETVAL=$RETVAL||$?
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/lin_tape
	echo
	return $RETVAL
}

stop() {
	echo -n -e "Shutting down lin_tape...\n"
	[ -x /usr/bin/lin_taped ] && /usr/bin/lin_taped stop &&
	echo -n -e "lin_taped unloaded\n"
	[ -f /sys/module/lin_tape/parameters/lin_tape_as_sfmp ] &&
	SFMP=$(cat /sys/module/lin_tape/parameters/lin_tape_as_sfmp) && [ $SFMP -eq 1 ] &&
	modprobe -f -r sgmp && modprobe -f -r stmp
	RETVAL=$RETVAL||$?
	modprobe -f -r lin_tape >/dev/null && modprobe -f -r pfo >/dev/null
    rm -f /var/lock/subsys/lin_tape
	echo
	return $RETVAL
}

case "$1" in
    start)
	start
	;;
    stop)
	stop
	;;
    status)
	[ `lsmod | grep -q lin_tape` ] && echo "lin_tape.ko present"
	[ -x /usr/bin/lin_taped ] && /usr/bin/lin_taped status || :
	;;
    restart|reload)
    	stop
	start
	;;
    condrestart)
	[ -f /var/lock/subsys/lin_tape ] && $0 restart || :
	;;
    *)
	echo "Usage: $0 {start|stop|status|reload|restart|condrestart}\n"
	exit 1

esac

exit $?
#
