#!/bin/sh

VERSION=`/bin/get_key_value /etc.defaults/VERSION buildnumber`
WebMailDir="/var/packages/MailStation/target"
WebMailExt=${WebMailDir}/mail/ext
WebMailConf=${WebMailDir}/mail/config/config.inc.php
OLDVERSION=`grep ^version /var/packages/MailStation/INFO | cut -d'"' -f2 | cut -d'-' -f2`

if [ $OLDVERSION -lt 250 ]; then
	WebMailExt="${WebMailDir}/roundcubemail/ext"
	WebMailConf="${WebMailDir}/roundcubemail/config/config.inc.php"
	# before v201, roundcube's config file main.inc.php
	if [ $OLDVERSION -le 201 ]; then
		WebMailConf="${WebMailDir}/roundcubemail/config/main.inc.php"
	fi;
fi;

if [ $VERSION -lt 1527 ]; then
	echo "The failed installation is due to the old-of-date firmware version." > $SYNOPKG_TEMP_LOGFILE
	echo "Please update to the latest firmware." >> $SYNOPKG_TEMP_LOGFILE
	exit 1
fi


if [ $OLDVERSION -lt 16 ]; then
	echo "The failed installation is due to the old-of-date package version." > $SYNOPKG_TEMP_LOGFILE
	echo "Please remove this package and re-install the latest one." >> $SYNOPKG_TEMP_LOGFILE
	exit 1
fi

echo $OLDVERSION > /tmp/MailStation.upgrade

rm -f /tmp/MailStation.restore
CONFIG_KEY_LIST="extmailallow extmailperiod smtp_server smtp_port mail_domain"
for config_key in ${CONFIG_KEY_LIST}
do
	if [ $OLDVERSION -le 201 ]; then
		grep -E "rcmail_config.*'${config_key}'" ${WebMailConf}
		if [ $? -eq 0 ]; then
			grep -E "rcmail_config.*'${config_key}'" ${WebMailConf} | tail -n 1 | sed 's/$rcmail_config/$config/g' >> /tmp/MailStation.restore
		else
			grep -E "rcmail_config.*${config_key}" ${WebMailConf} | tail -n 1 | sed 's/$rcmail_config/$config/g' | sed "s/${config_key}/\'${config_key}\'/g" >> /tmp/MailStation.restore
		fi
	else
		grep -E "config.*'${config_key}'" ${WebMailConf}
		if [ $? -eq 0 ]; then
			grep -E "config.*'${config_key}'" ${WebMailConf} | tail -n 1 >> /tmp/MailStation.restore
		else
			grep -E "config.*${config_key}" ${WebMailConf} | tail -n 1 | sed "s/${config_key}/\'${config_key}\'/g" >> /tmp/MailStation.restore
		fi
	fi
done

PKG_VOL_TMP="/`/usr/bin/readlink /var/services/homes | /usr/bin/cut -d'/' -f2`/@tmp"
mkdir -p $PKG_VOL_TMP

mkdir -p /tmp/MailStation
/bin/cp -a ${WebMailExt} /tmp/MailStation
/bin/rm -rf /tmp/MailStation/ext/procmailrc /tmp/MailStation/ext/fetchmailrc

exit 0
