#!/bin/sh -e

conffile="/etc/psa/psa.conf"

if [ ! -f "$conffile" ]; then
	echo "ERROR: File '$conffile' doesn't found"
	echo "Plesk is not installed."
	exit 1
fi

vhosts_d="`awk '/HTTPD_VHOSTS_D/ {print $2}' < /etc/psa/psa.conf`"
product_d="`awk '/PRODUCT_ROOT_D/ {print $2}' < /etc/psa/psa.conf`"
src_d="$product_d/var/atmail"
dst_d="`readlink -f $vhosts_d/../atmail`"
conf_d="/etc/psa-webmail"
archive_f="$product_d/var/atmail_105.tar.gz"
logfile="/tmp/atmail.log"

if [ ! -e "/usr/local/psa/admin/sbin/webmailmng" ]; then
	echo "ERROR: webmailmng utility doesn't found"
	echo "Possibly not all packages were installed."
	exit 1
fi

if [ ! -d "/etc/psa/webmail" -a ! -d "/etc/psa-webmail" ]; then
	echo "ERROR: atmail is not installed"
	exit 1
fi 

if [ ! -d "/etc/psa-webmail" ]; then
	conf_d="/etc/psa/webmail"
fi

die()
{
	echo "failed. See '$logfile' for details."
	exit 1
}

set_perms()
{
	local user group
	user="apache"
	group="apache"
	if [ -f "/etc/debian_version" ]; then
		user="www-data"
		group="www-data"
	elif [ -f "/etc/SuSE-release" ]; then
		user="wwwrun"
		group="www"
	fi

	find $dst_d -type d -exec chmod 0755 {} \; >$logfile 2>&1 || die
	find $dst_d -type f -exec chmod 0644 {} \; >$logfile 2>&1 || die

	chown -R root:root $dst_d >$logfile 2>&1 || die
	chown -R $user:$group $dst_d/logs >$logfile 2>&1 || die
	chown -R $user:$group $dst_d/users/tmp >$logfile 2>&1 || die
}

echo -n "Trying to unpack atmail archive... "
cd $product_d/var && tar -zxf $archive_f >$logfile 2>&1 || die
echo "done"

echo -n "Trying to replace atmail virtual host directory... "
rm -rf $dst_d >$logfile 2>&1 || die
mkdir -p $dst_d >$logfile 2>&1 || die
cp -R $src_d/vhost/* $dst_d/ >$logfile 2>&1 || die
set_perms
echo "done"

echo -n "Trying to configure atmail... "
sed -e "s|@@DOCROOT@@|$dst_d|g" \
	< $src_d/etc/atmail.conf.in > $conf_d/atmail/atmail.conf

sed -e "s|@@DOCROOT@@|$dst_d|g" \
    -e "s|@@CONF_D@@|$conf_d|g" \
	< $src_d/vhost/libs/Atmail/Config.php.in > $dst_d/libs/Atmail/Config.php

cp -f $src_d/etc/atmail_vhost.conf $conf_d/atmail/
cp -f $src_d/etc/atmailcom_vhost.conf $conf_d/atmailcom/

/usr/local/psa/admin/sbin/webmailmng --remove --name=atmail >$logfile 2>&1
/usr/local/psa/admin/sbin/webmailmng --install --name=atmail >$logfile 2>&1 || die
/usr/local/psa/admin/sbin/webmailmng --enable --name=atmail >$logfile 2>&1 || die

echo done
