#!/bin/sh
#
# General start/stop script:
# - Set the correct name and path below
# - Set USAGE_STRING below and check the allowed states in the case block
# - adjust check_config to fail or copy a config file if it is missing
# - finally adjust everything if really necessary...
#
SERVICE_NAME="SdaService"
BINARY_FILE_NAME=SdaService
BINARY_FILE_PATH="/bin"
CONFIG_FILE_NAME=sda_service.conf
CONFIG_FILE_PATH="/etc/sda"
CLIENT_CERTIFICATE_PATH=$(ls $(xmllint --xpath "string(//Configuration/HubConnection/Certificates/@ClientCertificate)" ${CONFIG_FILE_PATH}/${CONFIG_FILE_NAME}) 2>/dev/null)
USER_CONFIG_FILE_PATH="/opt/userdata/etc/sda"
# if service check is true, start is only possible, if the enable file is present
# remember to activate allowed states enable / disable
CHECK_SERVICE_ENABLED=true
# The allowed services for the usage message. Eg. "start|stop|restart|enable|disable|status"
# restart_on_failure is only used internally, if the IscWebService is configured properly.
USAGE_STRING="start|stop|restart|enable|disable|status|restart_on_failure"

user_pre_start() {
	if [ "${USER_CONFIG_FILE_PATH}" != "" ]; then
		echo -n "Checking ${USER_CONFIG_FILE_PATH} ... "
		if [ -d "${USER_CONFIG_FILE_PATH}" ]; then
			echo "found."
		else
			echo "not found."
			echo -n "Creating ${USER_CONFIG_FILE_PATH} ... "
			mkdir -p "${USER_CONFIG_FILE_PATH}"
		fi
	fi
}

#### general parameter

CONFIG_FILE="${CONFIG_FILE_PATH}/${CONFIG_FILE_NAME}"
BINARY_FILE="${BINARY_FILE_PATH}/${BINARY_FILE_NAME}"
SERVICE_ENABLED="/opt/userdata/.${SERVICE_NAME}-enabled"
PID_FILE="/var/run/${SERVICE_NAME}.pid"

log() {
	if [ "$(type logger)" != "" ]; then
		logger -t "${SERVICE_NAME}" "$1"
	else
		echo "$1"
	fi
}

log_std() {
	if [ "$(type logger)" != "" ]; then
		logger -t "${SERVICE_NAME}" "$1"
		echo "$1"
	else
		echo "$1"
	fi
}

# Check that the service exists.
if [ ! -f ${BINARY_FILE} ]; then
	log "Service not installed!"
	log_std "failure"
	exit 1
fi

check_config() {
	# if directory is missing, create it... the next test will fail.
	# check config directory
	if [ -d "${CONFIG_FILE_PATH}" ]; then
		log "${CONFIG_FILE_PATH} found."
	else
		log "${CONFIG_FILE_PATH} not found."
		log "Creating ${CONFIG_FILE_PATH}."
		mkdir -p "${CONFIG_FILE_PATH}"
	fi
	# check for valid configuration file; fail if not present
	if [ ! -f ${CONFIG_FILE} ]; then
		log "Configfile ${CONFIG_FILE} not found - can not start the service!"
		log_std "failure"
		exit 1
	fi
	log "Configfile ${CONFIG_FILE} found."
	log "Check if certificate is present:"
	if [ ! -f "${CLIENT_CERTIFICATE_PATH}" ]; then
		log "Connector certificate not found... exit now!"
		log_std "failure"
		exit 1
	fi
	log "Certificate found."
}

start() {
	log "Try to start service ${SERVICE_NAME}."
	if [ "${CHECK_SERVICE_ENABLED}" == "true" ]; then
		if [ ! -f ${SERVICE_ENABLED} ]; then
			log "Service is disabled!"
			log_std "failure"
			exit 1
		fi
	fi
	check_config
	user_pre_start
	log "Try stop previous ${SERVICE_NAME}."
	stop
	log "Starting ${SERVICE_NAME}"
	FW_VERSION=$(cat /opt/extparam/booted_application_version 2>/dev/null)
	MANUFACTURER_ID=$(cat /opt/extparam/manufacturer_id 2>/dev/null)
	DEVICE_ID=$(cat /opt/extparam/device_id 2>/dev/null)
	PRODUCT_ID=${MANUFACTURER_ID}${DEVICE_ID}
	OPT_PARAMS=""
	if [ "$FW_VERSION" != "" ]; then
		OPT_PARAMS="--firmwareversion ${FW_VERSION}"
	else
		log "Booted firmware version file not found!"
	fi
	if [ "$PRODUCT_ID" != "" ]; then
		OPT_PARAMS="${OPT_PARAMS} --platform ${PRODUCT_ID}"
	else
		log "Manufacturer and device id files not found!"
	fi
	${BINARY_FILE} -f ${CONFIG_FILE} -d ${OPT_PARAMS}
	RETVAL=$?
	pidof ${BINARY_FILE_NAME} > ${PID_FILE}
	if [ "$?" != "0" ]; then
		log_std "failed"
		return $RETVAL
	fi
	log_std "done"
	return $RETVAL
}

stop() {
	log "Stopping service ${BINARY_FILE_NAME}."
	rm -f ${PID_FILE}
	killall -9 ${BINARY_FILE_NAME}
	RETVAL=$?
	log_std "done"
	return $RETVAL
}

restart() {
	log "Restarting service ${BINARY_FILE_NAME}."
	stop
	start
	return $?
}

disable() {
	log "Disable service ${SERVICE_NAME}."
	if [ "${CHECK_SERVICE_ENABLED}" == "true" ]; then
		rm -rf ${SERVICE_ENABLED}
		if [ "$?" == "0" ]; then
			log_std "done"
		else
			log_std "failure"
			exit 1
		fi
	else
		log_std "not available"
	fi
}

enable() {
	log "Enable service ${SERVICE_NAME}."
	if [ "${CHECK_SERVICE_ENABLED}" == "true" ]; then
		touch ${SERVICE_ENABLED}
		if [ "$?" == "0" ]; then
			log_std "done"
		else
			log_std "failure"
			exit 1
		fi
	else
		log_std "not available"
	fi
}

status() {
	SERVICE_STATUS="stopped"
	SERVICE_MODUS="disabled"
	RETVAL=0
	if [ "${CHECK_SERVICE_ENABLED}" == "true" ]; then
		if [ -f ${SERVICE_ENABLED} ]; then
			SERVICE_MODUS="enabled"
		fi
	fi
	CHECK=$(pidof ${BINARY_FILE_NAME})
	if [ "${CHECK}" != "" ]; then
		# assume running because we found a pid
		SERVICE_STATUS="running"
		# save the pid if we have no pid file:
		if [ ! -f ${PID_FILE} ]; then
				pidof ${BINARY_FILE_NAME} > ${PID_FILE}
		fi
	else
		# ok, not running... should it run?
		if [ -f ${PID_FILE} ]; then
			# ups should run but not running
			SERVICE_STATUS="failure"
			RETVAL=1
		fi
	fi
	# status did not report in /var/log/messages!
	if [ "${CHECK_SERVICE_ENABLED}" == "true" ]; then
		echo "${SERVICE_MODUS} / ${SERVICE_STATUS}"
	else
		echo "${SERVICE_STATUS}"
	fi
	exit ${RETVAL}
}

restart_on_failure() {
	SERVICE_STATUS="stopped"
	SERVICE_MODUS="disabled"
	RETVAL=0
	if [ "${CHECK_SERVICE_ENABLED}" == "true" ]; then
		if [ -f ${SERVICE_ENABLED} ]; then
			SERVICE_MODUS="enabled"
		fi
	fi
	CHECK=$(pidof ${BINARY_FILE_NAME})
	if [ "${CHECK}" != "" ]; then
		# assume running because we found a pid
		SERVICE_STATUS="running"
		# save the pid if we have no pid file:
		if [ ! -f ${PID_FILE} ]; then
				pidof ${BINARY_FILE_NAME} > ${PID_FILE}
		fi
	else
		# ok, not running... should it run?
		if [ -f ${PID_FILE} ]; then
			SERVICE_STATUS="restarted"
			log_std "Restarted due to failure."
			restart
			RETVAL=$?
		fi
	fi
	# restart_on_failure did not report in /var/log/messages!
	if [ "${CHECK_SERVICE_ENABLED}" == "true" ]; then
		echo "${SERVICE_MODUS} / ${SERVICE_STATUS}"
	else
		echo "${SERVICE_STATUS}"
	fi
	exit 0
}

case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        restart
        ;;
  enable)
        enable
        ;;
  disable)
        disable
        ;;
  status)
        status
        ;;
  restart_on_failure)
        restart_on_failure
        ;;
  *)
        log_std "Usage: $0 {${USAGE_STRING}}"
        exit 1
esac

exit $?
