#!/bin/bash

. /var/packages/MailPlus-Server/scripts/UpgradeUtil.sh

PRIVATE_LOCATION="/var/packages/MailPlus-Server/target"
SYNONET_BINARY="/usr/syno/sbin/synonet"

VOLUME=`/usr/bin/readlink ${PRIVATE_LOCATION} | /usr/bin/cut -d '/' -f2`
VOLUME_MAILPLUS_SERVER_PATH="/${VOLUME}/@MailPlus-Server"

#license
UPGRADE_LICENSE_FLAG="/tmp/mailplus_server.upgrade_to_license_version"

RemoveConfigurationFiles()
{
	# maillog utility config files
	rm -f "/usr/local/etc/syslog-ng/patterndb.d/synolog/mailplus_server_event_log.conf"
	rm -f "/usr/local/etc/logrotate.d/mailplus_server_event_rotate.conf"

	# libmailplus
	rm -f "/usr/local/lib/mailplus"
}

RemoveServerSettings()
{
	rm -rf /usr/syno/etc/packages/MailPlus-Server/
	rm -rf /var/spool/@MailPlus-Server/cluster/
	rm -rf /var/spool/@MailPlus-Server/postfix/
	rm -rf /var/spool/@MailPlus-Server/audit/
	rm -rf /var/spool/@MailPlus-Server/alias_bkp/
}

RemoveServerLogs()
{
	rm -rf "/${VOLUME}/@maillog"
	rm -rf /var/spool/@MailPlus-Server/aggr_log
}

RemoveWholeVolumeFolder()
{
	rm -rf "${VOLUME_MAILPLUS_SERVER_PATH}"
}

RemoveAllPersonalMails()
{
	# remove MailPlus shared folder entirely
	/usr/syno/sbin/synoshare --del TRUE MailPlus
}

# uninstall would clean backend related dir
if [ ! -e ${UPGRADE_FILE} ] ; then
	# if user choose clearing all data, remove the volume folder entirely
	[ "$pkgwizard_remove_settings" = true ] && RemoveServerSettings
	[ "$pkgwizard_remove_logs" = true ] && RemoveServerLogs

	if [ "$pkgwizard_remove_settings" = true ] && [ "$pkgwizard_remove_logs" = true ]; then
		RemoveWholeVolumeFolder
	fi

	[ "$pkgwizard_remove_personal_data" = true ] && RemoveAllPersonalMails

	# unblock register iterface
	hostInetList=$(synonet --show | grep "Network interface:" | awk -F": " '{print $2}')
	for inet in ${hostInetList}; do
		${SYNONET_BINARY} --set_block ${inet} mailplus false 2>/dev/null
	done

	rm -f "$UPGRADE_LICENSE_FLAG"
fi

# remove link
rm -f /var/spool/@MailPlus-Server

RemoveConfigurationFiles

exit 0
