#!/bin/sh

SZD_PMA="/var/packages/phpMyAdmin"
DESKTOP="/usr/syno/synoman/webman/3rdparty/phpMyAdmin"
phpMyAdminTarget="${SZD_PMA}/target"
phpMyAdminUI="${phpMyAdminTarget}/ui"
DSM_INDEX_ADD="/usr/syno/bin/pkgindexer_add"
DSM_INDEX_DEL="/usr/syno/bin/pkgindexer_del"
WEBDIR="/var/services/web/phpMyAdmin"
NGINX_CONF_DIR="/usr/local/etc/nginx/conf.d/"
NGINX_ENALBE_CONF="www.phpMyAdmin.enable.conf"
NGINX_DISABLE_CONF="www.phpMyAdmin.disabled.conf"

ReturnBroken() {
	if [ "$SYNOPKG_DSM_VERSION_BUILD" -lt 2610 ]; then
		exit 2
	else
		exit 150
	fi
}

CheckEnv() {
	[ -f "/etc.defaults/VERSION" ] || exit 1
	DSM_VERSION=`grep ^majorversion= /etc.defaults/VERSION | cut -d'"' -f2`
	[ -z "$DSM_VERSION" ] && exit 1

	if [ $DSM_VERSION -ge 5 ]; then
		if [ ! -f /var/packages/MariaDB/enabled ]; then
			echo "Please run MariaDB first." > $SYNOPKG_TEMP_LOGFILE
			exit 1
		fi
	fi
}

StartDaemons() {
	CheckEnv

	rm -f $DESKTOP
	if [ -d "$WEBDIR" ]; then
		if [ ! -z "$SYNOPKG_PKGNAME" -a -n "$SYNOPKG_DSM_VERSION_MAJOR" -a $SYNOPKG_DSM_VERSION_MAJOR -ge 4 ]; then
			ln -sf ${phpMyAdminUI} ${DESKTOP}
			${DSM_INDEX_ADD} ${phpMyAdminUI}/index.conf
		else
			ln -sf ${phpMyAdminTarget}/desktop ${DESKTOP}
		fi
	else
		echo "web/phpMyAdmin not found."> $SYNOPKG_TEMP_LOGFILE
		if [ "$SYNOPKG_DSM_VERSION_BUILD" -lt 2610 ]; then
			exit 2
		else
			exit 150
		fi
	fi

	rm -rf ${NGINX_CONF_DIR}/${NGINX_DISABLE_CONF}
	ln -sf ${phpMyAdminTarget}/synology_added/${NGINX_ENALBE_CONF} ${NGINX_CONF_DIR}
}

StopDaemons()
{
	if [ -n "$SYNOPKG_DSM_VERSION_MAJOR" -a $SYNOPKG_DSM_VERSION_MAJOR -ge 4 ]; then 
		${DSM_INDEX_DEL} ${phpMyAdminUI}/index.conf
	fi
	if [ ! -z "$SYNOPKG_PKGNAME" ]; then
		rm -f ${DESKTOP}
	fi

	rm -rf ${NGINX_CONF_DIR}/${NGINX_ENALBE_CONF}
	ln -sf ${phpMyAdminTarget}/synology_added/${NGINX_DISABLE_CONF} ${NGINX_CONF_DIR}
}
case "$1" in
	start)
		StartDaemons
		;;
	stop)
		StopDaemons
		;;
	restart)
		StopDaemons
		sleep 1
		StartDaemons
		;;
	status)
		if [ ! -d "/var/services/web/phpMyAdmin" ]; then
			rm -f $DESKTOP
			ReturnBroken
		fi
		exit 0
		;;
	log)
		LOGFILE="/tmp/phpMyAdmin.log"
		grep "phpMyAdmin:" /var/log/messages > ${LOGFILE}
		if [ $? -eq 0 ]; then
			echo "${LOGFILE}"
		fi
		;;
	*)
		echo "Usage: $0 {start|stop|restart|status|log}" >&2
		exit 1
		;;
esac

exit 0

