#!/bin/sh

if [ -z "$SYNOPKG_PKGNAME" ]; then
    PACKAGE_NAME="PhotoStation"
    PACKAGE_VER=`get_key_value "/var/packages/${PACKAGE_NAME}/INFO" "version"`
else
    PACKAGE_NAME=$SYNOPKG_PKGNAME
    PACKAGE_VER=$SYNOPKG_PKGVER
fi

DSM_CONFIG="/etc.defaults/synoinfo.conf"
PACKAGE_DIR="/var/packages/$PACKAGE_NAME"
PACKAGE_ENABLED="${PACKAGE_DIR}/enabled"
SYNO_SERVICE_TOOL="/usr/syno/sbin/synoservice"
SYNO_RELAYD="/usr/syno/sbin/synorelayd"
PKG_LAN_DIR="$PACKAGE_DIR/target/photo/language"
DSM_DIR="/usr/syno/synoman"
PHOTO_PKG_SETTINGS="/var/packages/${PACKAGE_NAME}/etc/settings.conf"
PHOTO_RUN_PPS_KEY="runpersonalphotostation"

PHOTO_APACHE_CONF="SYNO.SDS.PhotoStation.conf"
SITES_ENABLED_USER_DIR="/etc/httpd/sites-enabled-user"

SDK_PLUGIN_DIR="/usr/local/libexec"
SDK_PLUGIN_BIN="synophoto_sdk_share_set"

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"

PKG_STATUS=$SYNOPKG_PKG_STATUS

check_link_binary() {
	for f in $PACKAGE_DIR"/target/bin"/*; do
	    name=$(basename "$f")
	    if [ ! -e "/usr/syno/bin/"$name ]; then
		ln -sf  $f "/usr/syno/bin"
		echo "ln $f"
	    fi
	done

	( cd /usr/syno/bin/ ; ln -sf ../../../bin/tar . )
	( cd /usr/syno/bin/ ; ln -sf ../../bin/php . )
	( cd $PACKAGE_DIR/target/photo/blog/ ; ln -sf ../photo_login.php ./login.php )
	( cd $PACKAGE_DIR/target/photo/ ; ln -sf $DSM_DIR/webman/help/help.css . )
}

pkg_get_string() {
	local file=$1
	local key=$2
	grep $key $file | sed -n "s,^.*=\t'\(.*\)';,\1,p" | sed "s/\\\\'/'/g"
}

register_service_volume() {
	local volume=`/usr/bin/readlink /var/services/photo | /bin/sed  's,/@sharebin/photo$,,'`

	if [ ! -z "$volume" ]; then
		$SYNO_SERVICE_TOOL --regvol -n ${PACKAGE_NAME} -t SERVICE_PKG -p $volume  >/dev/null 2>&1
	fi
}

unregister_service_volume() {
	$SYNO_SERVICE_TOOL --unregvol -n ${PACKAGE_NAME} -t SERVICE_PKG >/dev/null 2>&1
}

add_relay_service() {
	$SYNO_RELAYD --add photo_http --add photo_https --hup
}

remove_relay_service() {
	$SYNO_RELAYD --remove photo_http --remove photo_https --hup
}

check_home_service() {
	runPPS=`/bin/get_key_value "$PHOTO_PKG_SETTINGS" "$PHOTO_RUN_PPS_KEY"`
	userHomeEnable=`/bin/get_key_value "/etc/synoinfo.conf" "userHomeEnable"`

	if [ "$runPPS" = "yes" ] && [ "$userHomeEnable" != "yes" ]; then
		# set run personal photo to no when user home is not enable
		/var/packages/PhotoStation/target/bin/synophoto_config -s "$PHOTO_RUN_PPS_KEY" -v "no"
	fi
}

check_video_convert_table() {
	/usr/bin/psql -U postgres photo -c "select count(1) from video_convert;" | /bin/grep "^     0$"
	hasVideoConvert=$?

	/usr/bin/psql -U postgres photo -c "select count(1) from video;" | /bin/grep "^     0$"
	hasVideo=$?

	if [ $hasVideo = 1 ] && [ $hasVideoConvert = 0 ]; then
		/usr/syno/bin/synoindex -P PhotoStation -R photo > /dev/null 2>&1
	fi
}

check_indexing_queue() {
	/bin/grep R:photo /var/spool/syno_indexing_queue* > /dev/null 2>&1
	ret=$?
	if [ $ret = 0 ]; then
		# restart related daemons, to ensure load pkg info
		/usr/syno/sbin/synoservicecfg --restart synoindexd
		/usr/syno/sbin/synoservicecfg --restart synomkthumbd
		/usr/syno/sbin/synoservicecfg --restart synomkflvd
	fi
}

set_upload_tmp_dir()
{
	#update ini file
	$PACKAGE_DIR"/target/bin/"$SDK_PLUGIN_BIN --set-upload-tmp-dir

	#insert sdk share_set plugin
	local SDK_DIR="$SDK_PLUGIN_DIR/share_set"
	if [ ! -d $SDK_DIR ]; then
		mkdir -p $SDK_DIR
	fi
	cp -f $PACKAGE_DIR"/target/bin/"$SDK_PLUGIN_BIN $SDK_DIR
}

unset_upload_tmp_dir()
{
	#remove sdk share_set plugin
	rm $SDK_PLUGIN_DIR/share_set/$SDK_PLUGIN_BIN
}

start_message()
{
	local lan_file="${PKG_LAN_DIR}/${SYNOPKG_DSM_LANGUAGE}.php"
	if [ -e $lan_file ]; then
		local enable_warning=$(pkg_get_string "$lan_file" "photo_enable_warning")
		local download_text=$(pkg_get_string "$lan_file" "photo_str_download_now")
		local model_name=`get_key_value $DSM_CONFIG "upnpmodelname"`
		local link="(<a href=\"http://www.synology.com/support/download/$model_name\" target=\"_blank\">$download_text</a>)"
		echo "$enable_warning $link" > $SYNOPKG_TEMP_LOGFILE
	fi
}

set_httpd_config()
{
	if [ ! -e $SITES_ENABLED_USER_DIR/$PHOTO_APACHE_CONF ]; then
		cp -f $PACKAGE_DIR"/target/etc/"$PHOTO_APACHE_CONF $SITES_ENABLED_USER_DIR
	fi
}

case $1 in
	start)
		# check enabled
		if [ ! -f $PACKAGE_ENABLED ]; then
			exit 0;
		fi

		#create photo share
		$SYNO_SERVICE_TOOL --setshare photo

		#set php upload tmp dir & sdk share_set plugin
		set_upload_tmp_dir

		#check httpd config exists in /etc/httpd/site-enabled-user
		set_httpd_config

		#check & link photo binary to /usr/syno/bin
		check_link_binary

		# index help and add help to dsm
		${DSM_INDEX_ADD} ${PKG_APP_PATH}/index.conf ${PKG_INDEXDB_PATH}/appindexdb

		/usr/syno/bin/synoindex_package.sh enable $PACKAGE_NAME

		# if indexing queue has R:photo, restart related daemons
		check_indexing_queue

		#check_and_update_db_recover
		$PACKAGE_DIR/target/photo_scripts/sql.sh

		#After PhotoStation enabled, check thumbnails
		if [ "START" == "$PKG_STATUS" ] || [ "INSTALL" == "$PKG_STATUS" ]; then
			/usr/syno/bin/synoindex -P PhotoStation -R photo > /dev/null 2>&1
		fi

		#message for package start complete
		start_message

		/usr/syno/bin/photostationd

		register_service_volume

		# check home service and personal photo
		check_home_service

		# check if indexing queue has R:photo
		check_video_convert_table

		add_relay_service

		exit 0
	;;
	stop)
		if [ -n "$SYNOPKG_PKG_STATUS" ]; then
			${DSM_INDEX_DEL} ${PKG_APP_PATH}/index.conf ${PKG_INDEXDB_PATH}/appindexdb
		fi

		killall photostationd > /dev/null
		killall facerecognition > /dev/null

		remove_relay_service

		# check enabled
		if [ -f $PACKAGE_ENABLED ]; then
			exit 0;
		fi

		/usr/syno/bin/synoindex_package.sh disable $PACKAGE_NAME

		unregister_service_volume

		unset_upload_tmp_dir

		exit 0
	;;
	status)
		if [ -f ${PACKAGE_ENABLED} ]; then
			exit 0
		else
			exit 1
		fi
	;;
	killall)
        ;;
	log)
		exit 0
	;;
esac
