#!/bin/bash

### BEGIN INIT INFO
# Provides:          (>>>PROVIDES<<<)
# Required-Start:    (>>>REQ_START<<<)
# Required-Stop:     (>>>REQ_STOP<<<)
# Default-Start:     (>>>DEFAULT_START<<<)
# Default-Stop:      (>>>DEFAULT_STOP<<<)
# Short-Description: (>>>SHORT_DESCRIPTION<<<)
# Description:       (>>>DESCRIPTION<<<)
### END INIT INFO


# Include the LSB library functions
. /lib/lsb/init-functions


# Setup static variables
configFile='(>>>CONFIG_FILE<<<)'
daemonExec='(>>>DAEMON_EXEC<<<)'
daemonArgs='(>>>DAEMON_ARGS<<<)'
daemonName="$(basename "$daemonExec")"
pidFile='/var/run/(>>>FILE<<<).pid'


#
# Checks if the environment is capable of running the script (such as
# availability of programs etc).
#
# Return: 0 if the environmnt is properly setup for execution of init script, 1
#         if not all conditions have been met.
#
function checkEnvironment() {
    # Verify that the necessary binaries are available for execution.
    local binaries=((>>>REQ_BINARIES<<<))

    for bin in "${binaries[@]}"; do
        if ! which "$bin" > /dev/null; then
            log_failure_msg "Binary '$bin' is not available. Please install \
package containing it."
            exit 5
        fi
    done

    # Verify that the necessary environment variables have been set.
    local envVars=((>>>REQ_ENV_VARIABLES<<<))
    
    for var in "${envVars[@]}"; do
        if printenv "$var" > /dev/null; then
            log_failure_msg "Environment variable '$var' is not set. Please \
check your global environment settings."
            exit 6
        fi
    done
}


#
# Checks if the configuration files are available and properly setup.
#
# Return: 0 if irssid if properly configured, 1 otherwise.
#
function checkConfig() {
    # Make sure the configuration file has been created
    if ! [[ -f $configFile ]]; then
        log_failure_msg "Please populate the configuration file '$configFile' \
before running."
        exit 6
    fi

    # Make sure the required options have been set
    local reqOptions=((>>>REQ_OPTIONS<<<))
    for option in "${reqOptions[@]}"; do
        if ! grep -q -e "^[[:blank:]]*$option=" "$configFile"; then
            log_failure_msg "Mandatory option '$option' was not specified in \
'$configFile'"
            exit 6
        fi
    done
}


#
# Loads the configuration file and performs any additional configuration steps.
#
function configure() {
    . "$configFile"
    daemonCommand="$daemonExec $daemonArgs"
}


#
# Checks if the daemon is already running or not. If the daemon is running, its
# process id is stored within variable 'pid'.
#
# Return: 0 if the daemon is running, 1 otherwise.
#
function checkRunning() {
    for pid in $(pidofproc "$daemonExec"); do
        ps $pid | grep -qe "$daemonCommand" && return 0
    done
    return 1
}


#
# Starts the daemon.
#
# Return: LSB-compliant code.
#
function start() {
    start-stop-daemon --start --quiet --oknodo --pidfile "$pidFile" \
        --make-pidfile --exec "$daemonExec" -- $daemonArgs
}


#
# Stops the daemon.
#
# Return: LSB-compliant code.
#
function stop() {
    start-stop-daemon --stop --quiet --oknodo --retry 30 --pidfile "$pidFile" \
        --exec "$daemonExec" -- $daemonArgs
}


#
# Checks the status of the running daemon.
#
# Return: LSB-compliant status code.
#
function status() {
    status_of_proc -p "$pidFile" "$daemonExec" "$(basename $daemonExec)"
}


#
# Starts the daemon using custom code.
#
# Return: LSB-compliant code.
#
function startCustom() {
    if checkRunning; then
        return 0
    elif start-stop-daemon --start --quiet --pidfile $pidFile --make-pidfile \
        --exec "$daemonExec" -- $daemonArgs; then
        return 0
    else
        return 1
    fi
}


#
# Stops the daemon using custom code.
#
# Return: LSB-compliant code.
#
function stopCustom() {
    if checkRunning; then
        # Try to stop the daemon using SIGTERM first
        count=0
        while checkRunning && (( $count < 5 )); do
            kill $pid
            let count=count+1
            sleep 1
        done

        # If SIGTERM fails, use SIGKILL
        if checkRunning; then
            kill -9 $pid
            rm '/var/run/(>>>FILE<<<).pid'
            return 0
        else
            rm '/var/run/(>>>FILE<<<).pid'
            return 0
        fi 
    else
        return 0
    fi
}


#
# Checks the status of the running daemon.
#
# Return: LSB-compliant status code.
#
function statusCustom() {
    if checkRunning; then
        log_success_msg "irssid ($pid) is running"
        return 0
    else
        log_success_msg "irssid is not running"
        return 3
    fi
}


checkEnvironment
checkConfig
configure

case "$1" in
    start)
        log_daemon_msg "Starting daemon" "(>>>FILE<<<)"
        start && log_end_msg 0 || log_end_msg $?
        ;;
    stop)
        log_daemon_msg "Stopping daemon" "(>>>FILE<<<)"
        stop && log_end_msg 0 || log_end_msg $?
        ;;
    restart)
        log_daemon_msg "Restarting daemon" "(>>>FILE<<<)"
        stop
        start && log_end_msg 0 || log_end_msg $?
        ;;
    force-reload)
        log_daemon_msg "Restarting daemon" "(>>>FILE<<<)"
        stop
        start && log_end_msg 0 || log_end_msg $?
        ;;
    status)
        status && exit 0 || exit $?
        ;;
    *)
        echo "(>>>FILE<<<) (start|stop|restart|force-reload|status|help)"
        ;;
esac