#! /bin/sh
#
# bareos-ctl-dir This shell script takes care of starting and stopping
#		 the Bareos Director 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_DIRECTOR_BINARY="${BAREOS_DIRECTOR_BINARY:-/usr/sbin/bareos-dir}"
export BAREOS_CONFIG_DIR=${BAREOS_CONFIG_DIR:-/etc/bareos}
BAREOS_DIRECTOR_PORT=${BAREOS_DIRECTOR_PORT:-9101}
BAREOS_DIRECTOR_USER=${BAREOS_DIRECTOR_USER:-bareos}
BAREOS_DIRECTOR_GROUP=${BAREOS_DIRECTOR_GROUP:-bareos}
BAREOS_SCRIPT_DIR=${BAREOS_SCRIPT_DIR:-/etc/bareos/scripts}

#
# Source the generic functions.
#
. "${BAREOS_SCRIPT_DIR}/bareos-ctl-funcs"


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

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

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

            checkcfg
            if [ $? != 0 ]; then
                exit 1
            fi

            "${BAREOS_DIRECTOR_BINARY}" -v $2 $3 ${OPTIONS}
        fi
        ;;

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

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

    status)
        [ -x "${BAREOS_DIRECTOR_BINARY}" ] && status "${BAREOS_DIRECTOR_BINARY}" "${BAREOS_DIRECTOR_PORT}"
        exit $?
        ;;

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

exit 0
