#!/bin/bash
#
# zfs-share     This script will network share zfs filesystems and volumes.
#
# chkconfig:    2345 30 99
# description:  Run the `zfs share -a` or `zfs unshare -a` commands
#               for controlling iSCSI, NFS, or CIFS network shares.
# probe: true
#
### BEGIN INIT INFO
# Provides:       shareiscsi sharenfs sharesmb zfs-share
# Required-Start: $local_fs $network $remote_fs zvol
# Required-Stop:  $local_fs $network $remote_fs zvol
# Default-Start:  2 3 4 5
# Default-Stop:   0 1 6
# Should-Start:   iscsi iscsitarget istgt scst nfs-kernel-server samba samba4
# Should-Stop:    iscsi iscsitarget istgt scst nfs-kernel-server samba samba4
# Short-Description: Network share ZFS datasets and volumes.
# Description: Run the `zfs share -a` or `zfs unshare -a` commands
#      for controlling iSCSI, NFS, or CIFS network shares.
### END INIT INFO

# Source the common init script
. /etc/zfs/common.init
servicename=zfs-share

# ----------------------------------------------------

do_share()
{
	$log_begin_msg "Sharing ZFS filesystems"
	$ZFS share -a
	RET=$?

	if [ $RET != 0 ] ; then
		$log_failure_msg "Failed to share filesystems"
		$log_end_msg $RET
	fi

	$log_end_msg 0
}

do_unshare()
{
	$log_begin_msg "Unsharing ZFS filesystems"
	$ZFS unshare -a
	RET=$?

	# Ignore a non-zero `zfs` result so that a busy ZFS instance
	# does not hang the system during shutdown.
	if [ $RET != 0 ] ; then
		$log_end_msg $RET
	fi

	$log_end_msg 0
}

start()
{
	checksystem && {
		case "$ZFS_SHARE" in
			([Oo][Ff][Ff]|[Nn][Oo]|'')
				exit 0
				;;
		esac

		do_share

		touch "$LOCKDIR/$servicename"
	}
}

stop()
{
	case "$ZFS_UNSHARE" in
		([Oo][Ff][Ff]|[Nn][Oo]|'')
			exit 0
			;;
	esac

	# Do a more simplified version of checksystem()

	[ ! -f "$LOCKDIR/$servicename" ] && return 3

	# Check if ZFS is installed.  If not, comply to FC standards and bail
	zfs_installed || {
		$log_failure_msg "not installed"
		$log_end_msg 5
	}

	if ! grep -q zfs /proc/modules ; then
		# module not loaded, no need to unshare anything
		exit 0
	fi

	do_unshare

	rm -f "$LOCKDIR/$servicename"
}

case "$1" in
	(start)
		start
		;;
	(stop)
		stop
		;;
	(force-reload|reload|restart|status)
		# no-op
		;;
	(*)
		[ -n "$1" ] && echo "Error: Unknown command $1."
		echo "Usage: $0 {start|stop}"
		exit 3
		;;
esac
