#! /bin/sh
#
# bareos-ctl-sd  This shell script takes care of starting and stopping
#		 the Bareos Storage daemon
#
# description: Backup Archiving REcovery Open Sourced.
#

export PSCMD="/bin/ps -e"
export PS="ps"
export AWK="/usr/bin/awk"
export PIDOF="/bin/pidof"
export PGREP="/usr/bin/pgrep"

SUBSYSDIR=/var/lock
BAREOS_STORAGEDAEMON_BINARY=${BAREOS_STORAGEDAEMON_BINARY:-/usr/sbin/bareos-sd}
export BAREOS_CONFIG_DIR=${BAREOS_CONFIG_DIR:-/etc/bareos}
BAREOS_SD_PORT=${BAREOS_SD_PORT:-9103}
BAREOS_SD_USER=${BAREOS_SD_USER:-bareos}
BAREOS_SD_GROUP=${BAREOS_SD_GROUP:-bareos}
BAREOS_SCRIPT_DIR=${BAREOS_SCRIPT_DIR:-/etc/bareos/scripts}

#
# Source the generic functions.
#
. /etc/bareos/scripts/bareos-ctl-funcs

case "$1" in
    start)
        if [ -x ${BAREOS_STORAGEDAEMON_BINARY} ]; then
            echo "Starting the Bareos Storage daemon"
            OPTIONS=''
            if [ "${BAREOS_SD_USER}" != '' ]; then
                OPTIONS="${OPTIONS} -u ${BAREOS_SD_USER}"
            fi

            if [ "${BAREOS_SD_GROUP}" != '' ]; then
                OPTIONS="${OPTIONS} -g ${BAREOS_SD_GROUP}"
            fi

            if [ "${BAREOS_CONFIG_DIR}" != '' ]; then
                OPTIONS="${OPTIONS} -c ${BAREOS_CONFIG_DIR}"
            fi

            if [ "x${VALGRIND_SD}" = "x1" ]; then
                valgrind --leak-check=full ${BAREOS_STORAGEDAEMON_BINARY} -v $2 $3 ${OPTIONS}
            else
                ${BAREOS_STORAGEDAEMON_BINARY} -v $2 $3 ${OPTIONS}
            fi
        fi
        ;;

    stop)
        if [ -x ${BAREOS_STORAGEDAEMON_BINARY} ]; then
            printf "Stopping the Bareos Storage daemon: "
	    shift # shift away the stop
            killproc ${BAREOS_STORAGEDAEMON_BINARY} ${BAREOS_SD_PORT} "${@}"
        fi
        ;;

    restart)
        $0 stop
        sleep 5
        $0 start
        ;;

    status)
        [ -x ${BAREOS_STORAGEDAEMON_BINARY} ] && status ${BAREOS_STORAGEDAEMON_BINARY} ${BAREOS_SD_PORT}
        exit $?
        ;;

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

exit 0
