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

PACKAGE_DIR="/var/packages/MailStation"
WebMailEnabled="$PACKAGE_DIR/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"
PHP_CONF_DIR="/usr/local/etc/php56/conf.d/"
NGINX_CONF_DIR="/usr/syno/etc/www/app.d/"

FetchBin="/usr/syno/bin/synofetch"

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

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)
			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
			${FetchBin} ${popusr} $1
		fi
	done

}

StartDaemons() {

	cp -a ${WebMailDir}/bin/synofetch ${FetchBin}
}

CheckEnv()
{
	if [ ! -f "${WebMailEnabled}" ]; then
		exit 1
	fi

	if [ ! -f "/var/packages/MailServer/enabled" ]; then
		GenerateMessage "require_service"
		exit 1;
	fi
}

Start()
{
	CheckEnv

	StartDaemons
	POP3FetchControl -1

	${DSM_INDEX_ADD} ${WebMailDir}/ui/index.conf
	if [ -d ${PHP_CONF_DIR} ]; then
		ln -sf "$PACKAGE_DIR/target/etc/SYNO.SDS.MailStation.ini" "${PHP_CONF_DIR}"
	fi

	cp -f "${PACKAGE_DIR}/target/etc/MailStation.json" "$NGINX_CONF_DIR"
	cp -f "${PACKAGE_DIR}/target/etc/MailStation.mustache" "$NGINX_CONF_DIR"
}

case "$1" in
	start)
		Start
		;;
	stop)
		killall fetchmail
		if [ -f "${WebMailEnabled}" ]; then
			exit 0
		fi
		${DSM_INDEX_DEL} ${WebMailDir}/ui/index.conf
		rm -f "$PHP_CONF_DIR/SYNO.SDS.MailStation.ini"
		rm -f "$NGINX_CONF_DIR/MailStation.json"
		rm -f "$NGINX_CONF_DIR/MailStation.mustache"

		;;
	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

