#!/bin/sh

. /etc/domotz.env

LOG_FILE="${DOMOTZ_LOG_DIR}/${DPREFIX}status.log"

domotz_update_listener_port() { # $1 = Port number

	PACKAGE_INFO_FILE="/var/packages/domotz/INFO"
    sed -i -e "s/^adminport=.*/adminport=$1/g" ${PACKAGE_INFO_FILE}

	PACKAGE_WEB_INDEX_TEMPLATE="${DOMOTZ_ROOT_DIR}/ui/index.html.template"
	PACKAGE_WEB_INDEX="${DOMOTZ_ROOT_DIR}/ui/index.html"
    sed -e "s/PORT_REPLACE/$1/g" ${PACKAGE_WEB_INDEX_TEMPLATE} \
    		> ${PACKAGE_WEB_INDEX} 2>> ${LOG_FILE}

	PACKAGE_DSM_VERSION="${SYNOPKG_DSM_VERSION_MAJOR}.${SYNOPKG_DSM_VERSION_MINOR}"
	PACKAGE_CONFIG_TEMPLATE="${DOMOTZ_ROOT_DIR}/ui/config.template"
	PACKAGE_CONFIG="${DOMOTZ_ROOT_DIR}/ui/config"

	if [ "${PACKAGE_DSM_VERSION}" = "6.0" ]; then
		PACKAGE_CONFIG_URL="webman/3rdparty/domotz/index.html"
	else
		PACKAGE_CONFIG_URL="3rdparty/domotz/index.html"
	fi

    sed -e "s|URL_REPLACE|${PACKAGE_CONFIG_URL}|g" ${PACKAGE_CONFIG_TEMPLATE} \
    		> ${PACKAGE_CONFIG} 2>> ${LOG_FILE}
}

case $1 in
    start)
		domotz_start "/var/packages/domotz/scripts/start-stop-status"
		exit $?
        ;;
    stop)
        domotz_stop
        exit $?
        ;;
    restart)
        $0 stop; sleep 2; $0 start
        exit $?
        ;;
    status)
        domotz_status
        exit $?
   		;;
    *)
        exit 1
        ;;
esac