#!/bin/sh

# Copyright (C) 2015, Wazuh Inc.
# Wazuh         Controls Wazuh
# Author:       Daniel B. Cid <dcid@ossec.net>
# Modified for Debian by Michael Starks (patch by Costas Drogos)

### BEGIN INIT INFO
# Provides:          wazuh
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Should-Start:      $network
# Should-Stop:       $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start and stop Wazuh
# Description:       Controls Wazuh daemons
#
### END INIT INFO

WAZUH_HOME=/var/ossec
WAZUH_CONTROL="$WAZUH_HOME/bin/wazuh-control"

# Raise the soft file descriptor limit to the 65536 wazuh-agent.service uses, without lowering
# a higher limit already granted; below that ceiling, keep what the host allows and say so.
raise_nofile() {
    soft=$(ulimit -Sn)
    hard=$(ulimit -Hn)
    if [ "$soft" = "unlimited" ] || [ "$soft" -ge 65536 ] 2>/dev/null; then
        return 0
    fi
    if [ "$hard" = "unlimited" ] || [ "$hard" -ge 65536 ] 2>/dev/null; then
        ulimit -Sn 65536
    else
        ulimit -Sn "$hard"
        echo "wazuh-agent: file descriptor limit is $hard, below 65536; raise it with ulimit -n or LimitNOFILE" >&2
    fi
}

start() {
    raise_nofile
    ${WAZUH_CONTROL} start
}

stop() {
    ${WAZUH_CONTROL} stop
}

status() {
    ${WAZUH_CONTROL} status
}

case "$1" in
start)
    start
    ;;
stop)
    stop
    ;;
restart)
    stop
    start
    ;;
status)
    status
    ;;
*)
    echo "*** Usage: $0 {start|stop|restart|status}"
    exit 1
esac
