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

. "$(dirname $0)"/common

updatedb()
{
	local DB_PATH="${PACKAGE_DIR}/etc/etc-volume/synofinder.db"
	local DB_UPDATER="${TOOL_DIR}/synofinderdb"

	${TOOL_DIR}/synofinderdb -a update -v 1 -d "update synofinder.db"

	chown SynoFinder:SynoFinder ${DB_PATH}
	chmod 660 ${DB_PATH}
}

start()
{
	initctl start pkg-SynoFinder-synoelasticd
	${TOOL_DIR}/updater
	# FIXME: restarting is bad, achieve settings reloading with socket command
	initctl restart pkg-SynoFinder-synoelasticd
	${TOOL_DIR}/fileindex -a update_log_location -j "[]"
	${TOOL_DIR}/fileindex -a update_etc_location -j "[]"

	updatedb

	${TOOL_DIR}/fileindex -a prepare_services -d "start script prepare_services"
	${TOOL_DIR}/appindex -a try_reindex -d "start script try_reindex" &

	${TOOL_DIR}/appindex -a add -p ${TARGET_DIR}/ui/index.conf -d "start script add" &
}

stop()
{
	initctl stop pkg-SynoFinder-fileindexd
	initctl stop pkg-SynoFinder-synoelasticd

	${TOOL_DIR}/appindex -a del -p ${TARGET_DIR}/ui/index.conf -d "stop script del"
}

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

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

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

exit 0
