#!/bin/sh
# Copyright (c) 2000-2012 Synology Inc. All rights reserved.
PACKAGE_DIR="/var/packages/$SYNOPKG_PKGNAME"
DESKTOP="/usr/syno/synoman/webman/3rdparty/Piwik"
PKG_APP_PATH="${PACKAGE_DIR}/target/ui"
PKG_INDEXDB_PATH="${PACKAGE_DIR}/target/indexdb"
DSM_INDEX_ADD="/usr/syno/bin/pkgindexer_add"
DSM_INDEX_DEL="/usr/syno/bin/pkgindexer_del"
WEBDIR="/var/services/web/piwik"
SYNOLOGYADD="${PACKAGE_DIR}/target/synology_added/etc"
NGINX_ENABLE_CONF="www.Piwik.enable.conf"
NGINX_DISABLE_CONF="www.Piwik.disabled.conf"
NGINX_CONF_DIR="/usr/local/etc/nginx/conf.d/"

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

CheckEnv() {
	if [ ! -f /var/packages/MariaDB/enabled ]; then
		echo "Please run MariaDB first." > $SYNOPKG_TEMP_LOGFILE
		exit 1
	fi
}

StartDaemons() {
	CheckEnv
	
	if [ -d "$WEBDIR" ]; then
		ln -s ${PKG_APP_PATH} ${DESKTOP}
	else
		echo "web/piwik not found."> $SYNOPKG_TEMP_LOGFILE
		ReturnBroken
	fi

	if [ -n "$SYNOPKG_PKG_STATUS" ]; then
		${DSM_INDEX_ADD} ${PKG_APP_PATH}/index.conf ${PKG_INDEXDB_PATH}/appindexdb
	fi

	rm -rf $NGINX_CONF_DIR/$NGINX_DISABLE_CONF
	ln -sf $SYNOLOGYADD/$NGINX_ENABLE_CONF $NGINX_CONF_DIR
}

StopDaemons() {
	if [ -n "$SYNOPKG_PKG_STATUS" ]; then
		${DSM_INDEX_DEL} ${PKG_APP_PATH}/index.conf ${PKG_INDEXDB_PATH}/appindexdb
	fi
	rm $DESKTOP
	rm -rf $NGINX_CONF_DIR/$NGINX_ENABLE_CONF
	ln -sf $SYNOLOGYADD/$NGINX_DISABLE_CONF $NGINX_CONF_DIR
}

case "$1" in
	start)
		StartDaemons
		;;
	stop)
		StopDaemons
		;;
	restart)
		StopDaemons
		sleep 1
		StartDaemons
		;;
	status)
		if [ ! -d "$WEBDIR" ]; then
			rm $DESKTOP
			ReturnBroken
		fi
		exit 0
		;;
	log)
		echo ""
		;;
	*)
		echo "Usage: $0 {start|stop|restart|status}" >&2
		exit 1
		;;
esac
exit 0

