#!/bin/sh

### BEGIN INIT INFO
# Provides:          al-agent
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Alert Logic Collection Agent
### END INIT INFO

# Support chkconfig-based init script management (RHEL 5 and others)
# chkconfig: 2345 20 80
# description: Alert Logic Collection Agent

# Linux init.d script for Alert Logic Collector
# Copyright 2011-2014 Alert Logic, Inc.

#set -e
#set -x

PROD_DESC="Alert Logic Collection Agent"
MODE="agent"
DAEMON_NAME="al-agent"

# Uncomment to modify the default log level
#
# NOTE: This setting overrides centrally-managed remote configuration. The
# default setting is "info".
#
# debug|trace|info
#
#LOGLEVEL=debug

NAME=al-${MODE}
SYSTEMD_NAME=${NAME}.service
AL_ROOT=/var/alertlogic

PROD_ROOT=${AL_ROOT}/lib/${MODE}
DAEMON=${PROD_ROOT}/bin/${DAEMON_NAME}
DAEMON_ARGS="-d"

# local testing mode:
#DAEMON_ARGS="-H localhost -P 8080 -t linux --no-https"

PIDFILE=${PROD_ROOT}/run/$NAME.pid

if [ -n "$LOGLEVEL" ]
then
    DAEMON_ARGS="$DAEMON_ARGS -l $LOGLEVEL"
fi


# last ditch effort to get PID of daemon
my_pgrep() {
    PIDS=
    cmdlen=`expr length "$1"`
    while read pid tty time cmd rest; do
        if [ "$pid" != "$$" -a "`expr substr \"$cmd\" 1 $cmdlen`" = "$1" ]; then
            PIDS="$PIDS $pid"
        fi
    done <<MyPr0c355L1m1757r1n9
`ps -e`
MyPr0c355L1m1757r1n9
}


pidof_daemon() {
    # this is more reliable that `pidof $NAME`, because it looks for full path
    # (-f option)
    PIDS=`pgrep -f $DAEMON`

    if [ "$?" = "127" ]; then
        # pgrep does not execute
        my_pgrep $NAME
    fi

    PID=0
    if [ ! -e "$PIDFILE" ]
    then
        # take the first returned pid
        for i in $PIDS; do
            PID=$i
            break
        done
    else
        # take the pid that's also in the pid file
        PIDFILE_PID=`cat $PIDFILE`
        for i in $PIDS; do
            if [ "$i" = "$PIDFILE_PID" ]; then
                PID=$i
            fi
        done
    fi
}


is_running() {
    pidof_daemon

    if [ $PID -gt 0 ]
    then
        return 0 # true
    else
        return 1
    fi
}


log_start() {
    echo -n $1
}


log_end() {
    if [ $? -eq 0 ]; then
        echo "."
    else
        echo " failed!"
        exit 1
    fi
}


remove_pid_file() {
    rm -f "$PIDFILE"
}


# $1 = wait indefinitely (true/false)
wait_for_exit() {
    j=0

    while $1 || [ $j -lt 20 ]; do
        if is_running; then
            echo -n .
            j=`expr $j + 1`
            sleep 1
        else
            return 0 # exited
        fi
    done
    return 1 # not exited
}


verify_root() {
    if [ "$(id -u)" -ne 0 ]; then
        echo "Error: \"$1\" operation requires superuser privileges."
        exit
    fi
}


start() {
    log_start "Starting ${PROD_DESC} ($NAME)"
    if is_running
    then
        echo -e "\n$NAME is already running with pid $PID." 1>&2
        false; log_end
    fi
    remove_pid_file
    if pgrep "systemd\$" >/dev/null 2>&1 && systemctl is-enabled $SYSTEMD_NAME >/dev/null 2>&1; then
        systemctl start $SYSTEMD_NAME
    else
        $DAEMON $DAEMON_ARGS
    fi
    log_end
}


stop() {
    log_start "Stopping ${PROD_DESC} ($NAME)"
    if is_running; then
        if ! (pgrep "systemd\$" >/dev/null 2>&1 && systemctl stop $SYSTEMD_NAME && ! is_running); then
            kill -TERM $PID 2>/dev/null
            if ! wait_for_exit false; then
                # die Die DIE
                echo -n "not responding to TERM, issuing KILL"
                kill -KILL -$PID 2>/dev/null
                wait_for_exit true
            fi
        fi
    else
        echo -n " - not running"
    fi
    log_end
    remove_pid_file
}


status() {
    if is_running
    then
        echo "$NAME is running with pid $PID."
    else
        echo "$NAME is NOT running."
        exit 3
    fi
}


case "$1" in
    start|stop)
        verify_root $1
        $1
        ;;
    restart|reload|force-reload)
        verify_root $1
        stop
        start
        ;;
    status)
        status
        ;;
    provision|configure|validate)
        verify_root $1
        $DAEMON $@
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|reload|force-reload|provision|configure|validate}"
        exit 2
esac

# vim: et sw=4 ts=4 ft=sh
