#!/bin/sh

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

tmpdir="/usr/local/psa/tmp"
libdir="lib"
[ "`uname -m`" = "x86_64" -a -e "/usr/lib64" ] && libdir="lib64"

detect_mta()
{
	local mta_name str

	if which rpm >/dev/null 2>&1; then
		str="`rpm -qa|grep plesk-mail-[pq]c-driver`"
	fi
	if which dpkg >/dev/null 2>&1; then
		str="`dpkg --get-selections plesk-mail-[pq]c-driver | awk '{if ($2 == \"install\") {print $1}}'`"
	fi

	case "$str" in
		plesk-mail-pc-driver*) mta_name="postfix";;
		plesk-mail-qc-driver*) mta_name="qmail" ;;
		*)
			echo "WARNING!!! Unable to detect your MTA service driver. Microupdate will not be installed."
			return 1
		;;
	esac

	echo "$mta_name"
	return 0
}

prefix="`detect_mta`" || exit 0

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

# mailmng
for file in mailmng; do
	sum_new="`md5sum $tmpdir/${prefix}-$file | cut -d\  -f 1`"
	sum_old="`md5sum /usr/local/psa/admin/sbin/$file | cut -d\  -f 1`"
	if [ "$sum_old" != "$sum_new" ]; then 
		cp -f $tmpdir/${prefix}-$file /usr/local/psa/admin/sbin/$file
		$restorecmd /usr/local/psa/admin/sbin/$file
		changed=1
	fi
done

# all other
for file in mailsrv_entities_dump; do
	sum_new="`md5sum $tmpdir/${prefix}-$file | cut -d\  -f 1`"
	sum_old="`md5sum /usr/$libdir/plesk-9.0/$file | cut -d\  -f 1`"
	if [ "$sum_old" != "$sum_new" ]; then
		cp -f $tmpdir/${prefix}-$file /usr/$libdir/plesk-9.0/$file
		$restorecmd /usr/$libdir/plesk-9.0/$file
		changed=1
	fi
done

# Spamassassin
perllib="`perl -e 'use Config; print $Config{lc(SITELIB)};'`"
cp -f /usr/local/psa/tmp/CmdManageSA3.pm $perllib/Mail/SpamAssassin/CmdManageSA3.pm > /dev/null

if [ $changed -eq 1 ]; then
	echo -n "Restarting $prefix... "
	/etc/init.d/$prefix restart >/dev/null 2>&1 && echo "done" || echo "failed"
fi
