#!/bin/bash
# 1C:Enterprise Daemon script for Linux

# For registry on RPM-based systems with chkconfig
# chkconfig: ${DAEMON_runlevel:-} ${DAEMON_startlevel:-} ${DAEMON_stoplevel:-}

### BEGIN INIT INFO
# Provides: ${DAEMON_provides:-}
# Required-Start: $local_fs $network $remote_fs $named ${DAEMON_requiredstart:-}
# Required-Stop: $local_fs $network $remote_fs $named ${DAEMON_requiredstop:-}
# Should-Start: ${DAEMON_shouldstart:-}
# Should-Stop: ${DAEMON_shouldstop:-}
# Default-Start: ${DAEMON_defaultstart:-}
# Default-Stop: ${DAEMON_defaultstop:-}
# Short-Description: ${DAEMON_short_description:-}
# Description: ${DAEMON_description:-}
### END INIT INFO

LAUNCHER_START_EXEC="${DAEMON_launcherstart:-}"
LAUNCHER_STOP_EXEC="${DAEMON_launcherstop:-}"
USER="${DAEMON_username:-}"
PID_FILE="${DAEMON_pidfile:-}"
USAGE="Usage: service {start|stop|restart|force-reload|status}."

# Start function
do_start()
{
    su -l $USER -c "$LAUNCHER_START_EXEC"
}

# Stop function
do_stop()
{
    su -l $USER -c "$LAUNCHER_STOP_EXEC"
    # Deleting PID file, in case of forced stop
    if [[ -f "$PID_FILE" ]]; then
        rm $PID_FILE
    fi;
}

# Decide an action
case $1 in
    "")
        echo "Incorrect command. No action specified. $USAGE";
        exit 2;
        ;;
    start)
        if [[ -f "$PID_FILE" ]]; then
            echo "Can't start service. Service is already running."
            exit 0
        else
            do_start
        fi
        ;;
    status)
        if [[ -f "$PID_FILE" ]]; then
            echo "Service is running."
            exit 0
        else
            echo "Service is not running."
            exit 3
        fi
        ;;
    stop)
        if [[ -f "$PID_FILE" ]]; then
            do_stop
        else
            exit 0
        fi
        ;;
    restart)
        if [[ -f "$PID_FILE" ]]; then
            do_stop
            do_start
        else
            echo "Service is not running, will start the service."
            do_start
        fi
        ;;
    force-reload)
        # Launcher does not support reload, so it will restart application instead
        if [[ -f "$PID_FILE" ]]; then
            do_stop
            do_start
        else
            echo "Service is not running, will do nothing."
            exit 0
        fi
        ;;
    reload)
        echo "Action is not supported."
        exit 3
        ;;
    try-restart)
        echo "Action is not supported."
        exit 3
        ;;
    *)
        echo "Incorrect command. Action is invalid. $USAGE" >&2
        exit 2
        ;;
esac
