#!/bin/sh
# preinst script for daemontools
#
# see: dh_installdeb(1)

set -e
prefix=/usr
qmaildir=/var/indimail
logdir=/var/log/svc
servicedir=/service
rm=/bin/rm

# summary of how this script can be called:
#        * <new-preinst> `install'
#        * <new-preinst> `install' <old-version>
#        * <new-preinst> `upgrade' <old-version>
#        * <old-preinst> `abort-upgrade' <new-version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

ID=`id -u`
if [ $ID -ne 0 ] ; then
	echo "You are not root" >&2
	exit 1
fi

case "$1" in
    install|upgrade)
	if [ " $1" = " upgrade" ] ; then
		# shutdown svscan before upgrade
		# create .svscan.down so that we
		# can restore state after upgrade in postinst
		(
		if [ -f ${prefix}/sbin/initsvc ] ; then
			${prefix}/sbin/initsvc -status
		fi
		set +e
		${prefix}/bin/svok ${servicedir}/.svscan/log
		if [ $? -eq 0 ] ; then
			touch ${servicedir}/.svscan.down
			echo "preinst: Giving svscan exactly 5 seconds to exit nicely"
			if test -f /etc/init/svscan.conf
			then
				/sbin/initctl emit qmailstop
			elif test -f /etc/event.d/svscan
			then
				/sbin/initctl emit qmailstop
			elif test -f /etc/systemd/system/multi-user.target.wants/svscan.service
			then
				/bin/systemctl stop svscan
			elif test -x ${prefix}/sbin/initsvc
			then
				if [ -x /etc/init.d/svscan ] ; then
					${prefix}/sbin/initsvc -status || /etc/init.d/svscan stop || true
				else
					${prefix}/sbin/initsvc -status || true
				fi
				${prefix}/sbin/initsvc -off || true
			else
				if [ -x /etc/init.d/svscan ] ; then
					/etc/init.d/svscan stop
				fi
				/bin/grep "^SV:" /etc/inittab |/bin/grep svscan |/bin/grep respawn >/dev/null
				if [ $? -eq 0 ] ; then
					sed -i 's{^SV:{#SV:{' /etc/inittab
					if [ $? -eq 0 ] ; then
						/sbin/init q
					fi
				fi
			fi
			set -e
			sleep 5
		else
			echo "preinst: svscan not running"
		fi
		) >> /var/log/daemontools-setup.log 2>&1
		exit 0
	fi
	#
	# Create a users and groups. Do not report any problems if they already
	# exists.
	#
	(
	mkdir -p /tmp/daemontools
	chmod 700 /tmp/daemontools
	touch /tmp/daemontools/.install
	echo "Adding IndiMail users/groups"
	nscd_up=`ps -ef |grep nscd |grep -v grep|wc -l`
	if [ $nscd_up -ge 1 ] ; then
		if [ -x /etc/init.d/nscd ] ; then
			/etc/init.d/nscd stop
		fi
	fi
	/usr/bin/getent group nofiles   > /dev/null || /usr/sbin/groupadd nofiles  || true
	/usr/bin/getent passwd qmaill   > /dev/null || /usr/sbin/useradd -M -g nofiles  -d ${logdir}  -s /sbin/nologin qmaill || true
	if [ $nscd_up -ge 1 ] ; then
		if [ -x /etc/init.d/nscd ] ; then
			/etc/init.d/nscd start
		fi
	fi
	) > /var/log/daemontools-setup.log 2>&1
	;;

    abort-upgrade)
    ;;

    *)
        echo "preinst 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
