#!/bin/bash
#
# falcon-sensor        This starts and stops falcon-sensor
#
# chkconfig: 2345 5 95
# description: This starts the CrowdStrike falcon sensor.
# Provides:          falcon-sensor
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
#
# processname: /opt/CrowdStrike/falcon-sensor
# pidfile: /var/run/falcon-sensor.pid
#
# Return values according to LSB for all commands but status:
# 0 - success
# 1 - generic or unspecified error
# 2 - invalid or excess argument(s)
# 3 - unimplemented feature (e.g. "reload")
# 4 - insufficient privilege
# 5 - program is not installed
# 6 - program is not configured
# 7 - program is not running
#

PATH=/sbin:/bin:/usr/bin:/usr/sbin
prog="falcond"

# Source function library.
if [ -f /etc/init.d/functions ]; then
    . /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ]; then
    . /etc/rc.d/init.d/functions
elif [ -f /lib/lsb/init-functions ]; then
    . /lib/lsb/init-functions
else
        exit 0
fi

# Allow anyone to run status
if [ "$1" = "status" ]; then
    status falcond
    RETVAL=$?
    exit $RETVAL
fi

# Check that we are root ... so non-root users stop here
test $EUID = 0  ||  exit 4

RETVAL=0

start(){
    if ! /opt/CrowdStrike/falconctl -g --cid > /dev/null; then
        exit 6
    fi
    test -x /opt/CrowdStrike/falcond || exit 5

    # make sure we're not already running.
    if status falcond > /dev/null ; then
        exit 0
    fi
    echo -n $"Starting falcond: "

    # start, using kernel event source, in background
    daemon /opt/CrowdStrike/falcond
    RETVAL=$?
    echo
    if test $RETVAL = 0 ; then
        touch /var/lock/subsys/falcond
    fi
    return $RETVAL
}

stop(){
    echo -n $"Stopping falcond: "
    killproc -d 60 falcond
    RETVAL=$?
    echo
    rm -f /var/lock/subsys/falcond
    return $RETVAL
}

rotate(){
    echo -n $"Rotating logs: "
    killproc falcond -HUP
    RETVAL=$?
    echo
    return $RETVAL
}

restart(){
    stop
    start
}

condrestart(){
    [ -e /var/lock/subsys/falcond ] && restart
    return 0
}

# See how we were called.
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    rotate)
        rotate
        ;;
    condrestart|try-restart)
        condrestart
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|rotate}"
        RETVAL=3
esac

exit $RETVAL

