#!/bin/sh
#
# /etc/rc.d/zabbix-server: start/stop zabbix server
#

SSD=/sbin/start-stop-daemon
PROG=/usr/sbin/zabbix_server
PID=/run/zabbix/zabbix_server.pid
OPTS=" -f "

case $1 in
    start)
        [ ! -e /run/zabbix ] && install -d -o zabbix -g zabbix /run/zabbix

        WPID=$(echo $PROG | rev | cut -d  '/' -f1 | rev | xargs -I{} pidof {} | cut -d  '/' -f1 | rev | cut -d ' ' -f1 | rev)

        if [ -z $WPID ]; then
            rm -f $PID
        fi

        $SSD --start -b --exec $PROG -- $OPTS
        ;;
    stop)
        WPID=$(echo $PROG | rev | cut -d  '/' -f1 | rev | xargs -I{} pidof {} | cut -d  '/' -f1 | rev | cut -d ' ' -f1 | rev)

        if [ -z $WPID ]; then
            return
        else
            if [ ! -e $PID ]; then
                echo $WPID > $PID
            else
                if [ $(cat $PID) != $WPID ]; then
                    echo $WPID > $PID
                fi
            fi
        fi

        $SSD --stop -u zabbix -g zabbix --retry 10 --pidfile $PID
        ;;
    restart)
        $0 stop
        $0 start
        ;;
    status)
        $SSD --status --pidfile $PID
        case $? in
        0) echo "$PROG is running with pid $(cat $PID)" ;;
        1) echo "$PROG is not running but the pid file $PID exists" ;;
        3) echo "$PROG is not running" ;;
        4) echo "Unable to determine the program status" ;;
        esac
        ;;
    *)
        echo "Usage: $0 [start|stop|restart|status]"
        ;;
esac

# End of file
