#!/bin/sh

SZD_PSB="/var/packages/SQLBuddy"
DESKTOP="/usr/syno/synoman/webman/3rdparty/SQLBuddy"
SQLBuddyTarget="${SZD_PSB}/target"
SQLBuddyUI="${SQLBuddyTarget}/ui"
DSM_INDEX_ADD="/usr/syno/bin/pkgindexer_add"
DSM_INDEX_DEL="/usr/syno/bin/pkgindexer_del"

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
}

case "$1" in
	start)
		CheckEnv

		rm -f $DESKTOP
		if [ ! -z "$SYNOPKG_PKGNAME" -a -n "$SYNOPKG_DSM_VERSION_MAJOR" -a $SYNOPKG_DSM_VERSION_MAJOR -ge 4 ]; then
			ln -sf ${SQLBuddyUI} ${DESKTOP}
			${DSM_INDEX_ADD} ${SQLBuddyUI}/index.conf
		else
			ln -sf ${SQLBuddyTarget}/desktop ${DESKTOP}
		fi
		;;
	stop)
		if [ -n "$SYNOPKG_DSM_VERSION_MAJOR" -a $SYNOPKG_DSM_VERSION_MAJOR -ge 4 ]; then 
			${DSM_INDEX_DEL} ${SQLBuddyUI}/index.conf
		fi
		if [ ! -z "$SYNOPKG_PKGNAME" ]; then
			rm -f ${DESKTOP}
		fi
		;;
	restart) # do nothing
		;;
	status)
		if [ ! -f "${SZD_PSB}/enabled" ]; then
			exit 1
		fi
		;;
	log)
		LOGFILE="/tmp/SQLBuddy.log"
		grep "SQLBuddy:" /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

