#!/bin/sh
# Copyright (c) 2000-2014 Synology Inc. All rights reserved.

PACKAGE_DIR="/var/packages/$SYNOPKG_PKGNAME"
WPDir="${PACKAGE_DIR}/target"
WPDesktop="/usr/syno/synoman/webman/3rdparty/WordPress"
WPWEB="/var/services/web/wordpress"
PKG_APP_PATH="${PACKAGE_DIR}/target/ui"
DSM_INDEX_ADD="/usr/syno/bin/pkgindexer_add"
DSM_INDEX_DEL="/usr/syno/bin/pkgindexer_del"
SYNOLOGYADD="${WPDir}/synology_added/etc"
WPWEBEnabled="/var/services/web/wordpress/enabled"

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

	# DSM 4 use different config
	if [ $DSM_VERSION -le 4 ]; then
		SITES_ENABLED_USER_DIR="/usr/syno/etc/sites-enabled-user"
		WP_APACHE_CONF=$SYNOLOGYADD"/SYNO.SDS.WordPress.conf"
		ApacheUserScript="/usr/syno/etc/rc.d/S97apache-user.sh"

		if [ -d $SITES_ENABLED_USER_DIR ]; then
		   cp -f $WP_APACHE_CONF $SITES_ENABLED_USER_DIR
		   $ApacheUserScript restart > /dev/null 2>&1
		fi
	else
		if [ ! -f /var/packages/MariaDB/enabled ]; then
			echo "Please run MariaDB first." > $SYNOPKG_TEMP_LOGFILE
			exit 1
		fi
	
		PHP_CONF_DIR="/etc/php/conf.d"
		WP_PHP_CONF=$SYNOLOGYADD"/SYNO.SDS.WordPress.ini"

		if [ ! -f $PHP_CONF_DIR"/SYNO.SDS.WordPress.ini" ]; then
			mkdir -p $PHP_CONF_DIR
			cp -f $WP_PHP_CONF $PHP_CONF_DIR
			initctl restart php-fpm > /dev/null 2>&1
		fi
	fi
}

StartDaemons() {
	CheckEnv
	if [ -d "$WPWEB" ]; then
		ln -s ${PKG_APP_PATH} ${WPDesktop}
	else
		echo "web/wordpress not found."> $SYNOPKG_TEMP_LOGFILE
		exit 1
	fi

	if [ -n "$SYNOPKG_DSM_VERSION_MAJOR" -a $SYNOPKG_DSM_VERSION_MAJOR -ge 4 ]; then
		${DSM_INDEX_ADD} ${PKG_APP_PATH}/index.conf
	else
		ln -sf ${WPDir}/desktop $WPDesktop
	fi
	touch $WPWEBEnabled
}

StopDaemons() {
	if [ -n "$SYNOPKG_DSM_VERSION_MAJOR" -a $SYNOPKG_DSM_VERSION_MAJOR -ge 4 ]; then
		${DSM_INDEX_DEL} ${PKG_APP_PATH}/index.conf
	fi
	rm -f $WPDesktop
	rm $WPWEBEnabled
}

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

exit 0

