#!/bin/sh
# Copyright 2019-present HiveMQ GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

### BEGIN INIT INFO
# Provides:          hivemq
# Required-Start:
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: HiveMQ MQTT Broker Start Script
# Description:       This file is a init.d script for Debian-based linux systems
### END INIT INFO

set -e

. /lib/lsb/init-functions

BASEDIR=/opt/hivemq
NAME=hivemq
DESC="MQTT Broker"
DAEMON=/opt/hivemq/bin/run.sh
DAEMON_USER=hivemq
DAEMON_GROUP=hivemq
PID_FILE="/var/run/${NAME}.pid"

do_start()
{
    # Return
    #   0 if daemon has been started
    #   1 if daemon was already running
    #   2 if daemon could not be started
    start-stop-daemon --start --quiet --chuid $DAEMON_USER:$DAEMON_GROUP --pidfile $PID_FILE --make-pidfile \
        --background --oknodo --exec $DAEMON -- $DAEMON_ARGS
    return $?
}

do_stop()
{
    # Return
    #   0 if daemon has been stopped
    #   1 if daemon was already stopped
    #   2 if daemon could not be stopped
    #   other if a failure occurred
    start-stop-daemon --stop --signal 15 --retry 5 --quiet --pidfile $PID_FILE
    RETVAL="$?"
    [ "$RETVAL" = 0 ] && rm -f $PID_FILE
    [ "$RETVAL" = 2 ] && return 2
    return "$RETVAL"
}

case "$1" in
    start)
        log_daemon_msg "Starting $DESC" "$NAME"
        do_start
        case "$?" in
            0|1) log_end_msg 0 ;;
            2)  log_end_msg 1 ;;
        esac
        ;;
    stop)
        log_daemon_msg "Stopping $DESC" "$NAME"
        do_stop
        case "$?" in
            0|1) log_end_msg 0 ;;
            2) log_end_msg 1 ;;
        esac
        ;;
    status)
        status_of_proc -p $PID_FILE $DAEMON $NAME
        ;;
    restart|reload)
        log_daemon_msg "Restarting $DESC" "$NAME"
        do_stop
        case "$?" in
            0|1)
                do_start
                case "$?" in
                    0) log_end_msg 0 ;;
                    1) log_end_msg 1 ;; # Old process is still running
                    *) log_end_msg 1 ;; # Failed to start
                esac
                ;;
            *)
                # Failed to stop
                log_end_msg 1
                ;;
        esac
        ;;
    *)
        echo "Usage: $SCRIPTNAME {start|stop|restart|reload}" >&2
        exit 3
        ;;
esac

exit 0