#!/bin/sh

. "$(dirname $0)"/common

GenerateOldPkgVerFile()
{
	# touch temp file for old package version, it will be deleted after package start.
	# If it's a brand new install, SYNOPKG_OLD_PKGVER would be empty.
	touch ${OLD_PKGVER_FILE}
	OLD_VER_STR="old_version="${SYNOPKG_OLD_PKGVER}
	echo ${OLD_VER_STR} >> ${OLD_PKGVER_FILE}
	chmod 600 ${OLD_PKGVER_FILE}
}

GrantAllPrivilege()
{
	GRANT_ALL_PRIV_TOOL="${PACKAGE_DIR}/target/tool/grant_all_privilege"

	if [ -z ${SYNOPKG_OLD_PKGVER} ] ; then
		# it's a brand new install, grant default privilege to all users
		${GRANT_ALL_PRIV_TOOL}
	fi
}

UpgradePOP3FetchConfig()
{
        # fetchmail will be upgraded to 6.4 since version 2.2.0-1310,
        # we will need to upgrade pop3 fetchmail config to remove sslproto parameter for it will cause pop3 fetch process stop working.
		OLD_BUILD_NUMBER=`echo ${SYNOPKG_OLD_PKGVER} | awk -F'[.-]' '{print $NF}'`

		if [ -z ${OLD_BUILD_NUMBER} ] || [ $((10#${OLD_BUILD_NUMBER} % 10000)) -lt "1400" ]; then
			# to find all such files and modify the following items:
			# 1. remove all sslproto for ssl23 or tls1 won't work anymore and cause problem, just remove them
			# 2. add 'no sslcertck' on all recent configurations upgraded from 6.3. sslcertck is on by default in 6.4.
			sed -i 's/^[\t ]*sslproto .*/\tno sslcertck/g' /volume*/MailPlus/*/*/*/.SYNOMC/mailclient_pop3_fetch
		fi
}

FillLogFileFullPath()
{
	local PRIVATE_LOCATION="/var/packages/MailPlus-Server/target"
	local VOLUME=$(/usr/bin/readlink ${PRIVATE_LOCATION} | /usr/bin/cut -d'/' -f2)
	local MAILPLUS_LOG_PATH="/${VOLUME}/@maillog"
	local LOG_FILES=( "logrotate.conf" "syslog-ng.conf" )

	for file in "${LOG_FILES[@]}"
	do
		/bin/sed -i -e "s|__MAILPLUS_LOG_PATH__|${MAILPLUS_LOG_PATH}|g" "/var/packages/MailClient/target/etc/${file}"
	done
}

ModifyToolPermission()
{
	# setuid-root for gsuite migration tool
	chown root:MailPlus-Server "/var/packages/MailClient/target/tool/label_migration"
	chmod 4750 "/var/packages/MailClient/target/tool/label_migration"
}

GenerateOldPkgVerFile
GrantAllPrivilege
UpgradePOP3FetchConfig
FillLogFileFullPath
ModifyToolPermission

exit 0
