#!/bin/sh
VOLUME=`/usr/bin/readlink /var/services/homes | /usr/bin/cut -d'/' -f2`

PACKAGE_DIR="/var/packages/MailStation"
WebMailEnabled="$PACKAGE_DIR/mailstation_enabled"
WebMailDir="$PACKAGE_DIR/target"
WebmailDesktop="/usr/syno/synoman/webman/3rdparty/MailStation"
WebMailExt=${WebMailDir}/mail/ext
WebMailConf=${WebMailDir}/mail/config/config.inc.php
UIStringDir="$PACKAGE_DIR/target/ui/texts"
DSM_INDEX_ADD="/usr/syno/bin/pkgindexer_add"
DSM_INDEX_DEL="/usr/syno/bin/pkgindexer_del"
NGINX_CONF_DIR="/usr/local/etc/nginx/conf.d/"

FetchBin="/var/packages/MailStation/target/bin/synofetch"

popusers=`/usr/bin/find ${WebMailExt} -name "*_fetch" | /usr/bin/cut -d'/' -f8 | sed 's/.\{6\}$//'`

YES=0
NO=1

isDSM7OrAbove()
{
	local dsm_mayor_version="$(get_key_value /etc.defaults/VERSION majorversion)"

	if [[ "${dsm_mayor_version}" -gt 6 ]]; then
		return ${YES}
	else
		return ${NO}
	fi
}

isDSM7PackageEnabled()
{
	local package="${1:-MailStation}"
	local package_systemd_service="pkgctl-${package}"
	local systemd_status="$(systemctl is-active "${package_systemd_service}")"

	if [ "${systemd_status}" == "activating" ] || [ "${systemd_status}" == "active" ]; then
		return ${YES}
	else
		return ${NO}
	fi
}

isDSM6PackageEnabled()
{
	local package="${1:-MailStation}"
	local package_enabled_flag="/var/packages/${package}/enabled"

	if [ -f "${package_enabled_flag}" ]; then
		return ${YES}
	else
		return ${NO}
	fi
}

# "Enabled" including "starting" and "started"
isPackageEnabled()
{
	if isDSM7OrAbove; then
		isDSM7PackageEnabled "$@"
	else
		isDSM6PackageEnabled "$@"
	fi
}

# compatible with DSM6 & DSM 7
serviceCtl()
{
	local action="$1"
	local service="$2"
	if isDSM7OrAbove; then
		synosystemctl "${action}" "${service}"
	else
		initctl "${action}" "${service}"
	fi
}

GenerateMessage() {
	local key=$1
	case $SYNOPKG_DSM_LANGUAGE in
		chs | cht |csy | dan | enu | fre | ger | hun | ita | jpn | krn | nld | nor | plk| ptb | ptg | rus | spn | sve | trk | tha)
			echo $(sed -n '/^\[app\]/,/^'$key'/s/'$key'.*=.*"\(.*\)"/\1/p' $UIStringDir/$SYNOPKG_DSM_LANGUAGE/strings) > $SYNOPKG_TEMP_LOGFILE
			;;
		* )
			echo "This package requires you to enable Mail Server." > $SYNOPKG_TEMP_LOGFILE
			;;
	esac
}

POP3FetchControl(){
	POP3Fetch_enabled=`grep -E "config.*'extmailallow'" ${WebMailConf} | tr -d ' ' | cut -d '=' -f2`
	if [ "$POP3Fetch_enabled" != "true;" ]; then
		return
	fi
	for popusr in $popusers
	do
		if [ -e ${WebMailExt}/${popusr}_fetch ]; then
			# workaround for DSM 6.2.2 bug, it will reset all permissions as MailStation:MailStation ...
			# set owner back to the real owner. considering domain user specifically (avoid wrong backslash escape)
			chown ${popusr} ${WebMailExt}/${popusr}_fetch
			chown ${popusr} "${WebMailExt}"/"${popusr}".proc.*

			${FetchBin} ${popusr} $1
		fi
	done

}

StartDaemons() {
	serviceCtl start pkg-MailStation_php74_fpm

	if [ -f "/usr/syno/bin/synofetch" ]; then
		rm "/usr/syno/bin/synofetch"
	fi
	chown root:MailStation ${FetchBin}
	chmod 4750 ${FetchBin}
}

CheckEnv()
{
	# check if package is starting
	if ! isPackageEnabled; then
		exit 1
	fi

	if ! isPackageEnabled "MailServer"; then
		GenerateMessage "require_service"
		exit 1;
	fi
}

Start()
{
	CheckEnv

	touch "${WebMailEnabled}"
	chmod 644 "${WebMailEnabled}"

	StartDaemons
	POP3FetchControl -1

	${DSM_INDEX_ADD} ${WebMailDir}/ui/index.conf

	if ! isDSM7OrAbove; then
		cp -f "${PACKAGE_DIR}/target/etc/www.MailStation.conf" "${NGINX_CONF_DIR}"
	fi
}

case "$1" in
	start)
		Start
		;;
	stop)
		killall fetchmail

		serviceCtl stop pkg-MailStation_php74_fpm

		${DSM_INDEX_DEL} ${WebMailDir}/ui/index.conf
		if ! isDSM7OrAbove; then
			rm -f "$NGINX_CONF_DIR/www.MailStation.conf"
		fi

		rm "${WebMailEnabled}"
		;;
	restart)
		sleep 1
		StartDaemons
		;;
	status)
		if [ -f "${WebMailEnabled}" ]; then
			exit 0
		fi
		exit 1
		;;
	log) 
		echo ""
		;;  
	*)
		echo "Usage: $0 {start|stop|restart|status}" >&2
		exit 1
		;;
esac

exit 0

