#!/bin/sh

. /var/packages/Calendar/scripts/common

Control()
{
	if [ -f "/usr/syno/bin/synosystemctl" ]; then
		synosystemctl $*
	else
		initctl $*
	fi
}

stop_package()
{
	Control stop $PUSHSERVER_UPSTART_NAME
	Control stop $PHPFPM_UPSTART_NAME
	# remove index and help entry
	# worker should do
	#${DSM_INDEX_DEL} ${PKG_APP_PATH}/index.conf ${PKG_INDEXDB_PATH}/appindexdb
	#${DSM_INDEX_DEL} ${PKG_APP_PATH}/helptoc.conf ${PKG_INDEXDB_PATH}/helpindexdb
	
	#rm -f /usr/local/etc/logrotate.d/calendarserver
	#rm -f /usr/local/libexec/dirsvs_leave/synocarddav_dirsvs_hook.sh

	if [ ${SYNOPKG_DSM_VERSION_MAJOR} -lt 7 ]; then
		# unlink nginx conf
		rm /usr/local/etc/nginx/sites-enabled/calendar-nginx.conf
		rm /usr/local/etc/nginx/conf.d/www.Calendar.conf
		/bin/nginx -s reload
	fi
	$PKG_TOOL_DIR/synocalendar_tmp.sh drop
	exit 0
}



start_package()
{
	# reset syno_cal_notify
	$PKG_TOOL_DIR/synocalendar_tmp.sh create

	db_migration

	echo "== tuning timezone sequence ==" >> /var/log/synocal.log 2>&1
	${PKG_TOOL_DIR}/timezone-tunning.sh
	echo "== tuning todo-collection-tunning.sh ==" >> /var/log/synocal.log 2>&1
	${PKG_TOOL_DIR}/todo-collection-tunning.sh

	echo "== run syno-tz-check.php to add missing olson name tz ==" >> /var/log/synocal.log 2>&1
	/bin/sudo -u synocalendar /usr/local/bin/php74 -d open_basedir=/ /var/packages/Calendar/target/davical/scripts/syno-tz-check.php
	if [ ! -f $is_new_beginning_file ]; then
		echo "== reindex db ==" >> /var/log/synocal.log 2>&1
		$PSQL ${DBA} -d ${DBNAME} -c "reindex database calendar;"
	else
		/bin/rm $is_new_beginning_file
	fi
	Control start $PHPFPM_UPSTART_NAME
	Control start $PUSHSERVER_UPSTART_NAME
	
	# index help and add help to dsm
	# worker should do
	#${DSM_INDEX_ADD} ${PKG_APP_PATH}/index.conf ${PKG_INDEXDB_PATH}/appindexdb
	#${DSM_INDEX_ADD} ${PKG_APP_PATH}/helptoc.conf ${PKG_INDEXDB_PATH}/helpindexdb

	if [ ${SYNOPKG_DSM_VERSION_MAJOR} -lt 7 ]; then
		# link nginx conf
		ln -sf ${PKG_CONF_DIR}/calendar-nginx.conf /usr/local/etc/nginx/sites-enabled/
		# link nginx 80/443 rewrite rule
		ln -sf /etc/nginx/app.d/dsm.Calendar.conf  /usr/local/etc/nginx/conf.d/www.Calendar.conf
		/bin/nginx -s reload
	fi

	# script may kill all db connection, so we should restart daemon at final step
	Control stop $NOTIFYDAEMON_UPSTART_NAME
	Control stop $PUSHSERVER_UPSTART_NAME
	/bin/sleep 1
	Control start $PUSHSERVER_UPSTART_NAME
	Control start $NOTIFYDAEMON_UPSTART_NAME
	$PKG_TOOL_DIR/update_tz.sh local >> /var/log/synocal.log 2>&1

	exit 0
}

case $1 in
        start)
                start_package
                exit 0
                ;;
        stop)
                stop_package
                exit 0
                ;;
        status)
				if [ -e ${APP_PATH} ]; then
                        exit 0
                else
                        exit 1
                fi
                ;;
        log)
                exit 0
                ;;
esac

