#!/bin/sh
# prerm script for iscsitarget
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <prerm> `remove'
#        * <old-prerm> `upgrade' <new-version>
#        * <new-prerm> `failed-upgrade' <old-version>
#        * <conflictor's-prerm> `remove' `in-favour' <package> <new-version>
#        * <deconfigured's-prerm> `deconfigure' `in-favour'
#          <package-being-installed> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package


case "$1" in
    remove|upgrade|deconfigure)
    ;;
    failed-upgrade)
	# The iscsitarget init script matching this md5sum will exit non-zero
	# if the iscsi_trgt module cannot be unloaded, even if the daemon is killed.
	#
	# Compounding the issue is the fact that the iscsi_trgt module provided by
	# the Ubuntu kernel (circa Intrepid) does not unload properly (LP: #278625).
	#
	# Newer iscsitarget init scripts should handle this more gracefully.
	#
	# This maintainer-script code is intended to stop the iscsi target, and
	# ignore the module unloading error, and thus allow the upgrade to proceed.
	if md5sum /etc/init.d/iscsitarget 2>/dev/null | grep -qs "^f0f3eed8e9f7daddb7dcb31004633a16"; then
		# The old package's init script will succeed in stopping the daemon,
		# but fail in unloading the module.  Restart the daemon here
		/etc/init.d/iscsitarget start || true
		# Now try to stop it, capturing the output
		RC=0
		OUT=`/etc/init.d/iscsitarget stop 2>&1` || RC=$?
		# If the exit code is non-zero, and the error reported is the known
		# module issue, exit 0
		if [ "$RC" != "0" ]; then
			if echo "$OUT" | grep -qs "Module iscsi_trgt is in use"; then
				echo "WARNING: Ignoring the fact that module iscsi_trgt is in use"
				exit 0
			fi
		fi
		exit $RC
	fi
    ;;
    *)
	echo "prerm called with unknown argument \`$1'" >&2
	exit 1
    ;;
esac

	
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
