#!/bin/sh

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

# before v201, roundcube's config file main.inc.php
if [ $OLDVERSION -le 201 ]; then
	WebMailConf=${WebMailDir}/roundcubemail/config/main.inc.php
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

if [ $OLDVERSION -le 201 ]; then
	grep -E "rcmail_config.*extmailallow|rcmail_config.*extmailperiod|rcmail_config.*smtp_server|rcmail_config.*smtp_port|rcmail_config.*mail_domain" $WebMailConf | sed 's/$rcmail_config/$config/g' > /tmp/MailStation.restore
else
	grep -E "config.*extmailallow|config.*extmailperiod|config.*smtp_server|config.*smtp_port|config.*mail_domain" $WebMailConf > /tmp/MailStation.restore
fi

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
