#!/bin/sh

if [ -n "$PLESK_INSTALLER_DEBUG" -o -n "$PLESK_INSTALLER_VERBOSE" ]; then
	set -x;
fi

echo_msg()
{
	if [ -z "$PLESK_INSTALLER_DEBUG" -a -z "$PLESK_INSTALLER_VERBOSE" ]; then
		return 0
	fi

	echo "$*"
}

replace_bin()
{
	local src="$1"
	local dst="$2"	

	echo_msg "stopping qmail"
	/etc/init.d/qmail stop

	echo_msg "replacing qmail-queue"
	mv $src $dst
	chown mhandlers-user.popuser $dst
	chmod 2511 $dst

	which restorecon > /dev/null
	if [ $? = 0 ]; then
		restorecon $dst
	fi

	echo_msg "starting qmail"
	/etc/init.d/qmail start
}

qmail_bin="/var/qmail/bin/qmail-queue"
qmail_enabled="0"
qmail_sum=""

ctch_bin="/opt/ctch/ct-qmail-queue"
ctch_enabled="0"
ctch_sum=""

plesk_bin="/var/qmail/bin/qmail-queue.plesk.ctch"
plesk_sum=""

qmail_bin_new="/usr/local/psa/tmp/qmail-queue"
qmail_sum_new="`md5sum $qmail_bin_new | awk '{print $1}'`"

# is qmail enabled?
if [ -f "$qmail_bin" ]; then
	qmail_enabled="1"
	qmail_sum="`md5sum $qmail_bin | awk '{print $1}'`"
else
	echo_msg "qmail-queue not found, no need to replace"
	exit 0;
fi

# is commtouch enabled?
if [ -f "$ctch_bin" ]; then
	ctch_sum="`md5sum $ctch_bin | awk '{print $1}'`"
	if [ "$qmail_sum" = "$ctch_sum" ]; then
		ctch_enabled="1"
		plesk_sum="`md5sum $plesk_bin | awk '{print $1}'`"
	fi
fi

case "${qmail_enabled}${ctch_enabled}" in
	00|01) ;; # qmail not enabled
	10) # qmail on, ctch off
		if [ "$qmail_sum" = "$qmail_sum_new" ]; then
			echo_msg "qmail-queue is up to date, skipping"
			exit 0
		fi
		replace_bin "$qmail_bin_new" "$qmail_bin"
	;;
	11) # qmail on, ctch on
		if [ "$plesk_sum" = "$qmail_sum_new" ]; then
			echo_msg "qmail-queue is up to date, skipping"
			exit 0
		fi
		replace_bin "$qmail_bin_new" "$plesk_bin"
	;;
esac

exit 0
