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

export PSCMD="@PSCMD@"
export PS="ps"
export AWK="@AWK@"
export PIDOF="@PIDOF@"
export PGREP="@PGREP@"

BAREOS_DIRECTOR_BINARY="${BAREOS_DIRECTOR_BINARY:-@sbindir@/bareos-dir}"
export BAREOS_CONFIG_DIR=${BAREOS_CONFIG_DIR:-@confdir@}
BAREOS_DIRECTOR_PORT=${BAREOS_DIRECTOR_PORT:-@dir_port@}
BAREOS_SCRIPTS_DIR=${BAREOS_SCRIPTS_DIR:-@scriptdir@}
BAREOS_PIDFILE_PREFIX=${BAREOS_PIDFILE_PREFIX:-""}

if [ "${BAREOS_PIDFILE_PREFIX}" != '' ]; then
  BAREOS_PIDFILE="${BAREOS_PIDFILE_PREFIX}dir.pid"
  export BAREOS_PIDFILE
fi

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

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

      check_database dir ${BAREOS_DIRECTOR_BINARY} $2 $3 ${OPTIONS} || exit $?
      check_config dir ${BAREOS_DIRECTOR_BINARY} $2 $3 ${OPTIONS} || exit $?
      "${BAREOS_DIRECTOR_BINARY}" -v $2 $3 ${OPTIONS}
    else
      echo "${BAREOS_DIRECTOR_BINARY} not executable. Did you forget to build?" >&2
      exit 1
    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)
    if [ -x "${BAREOS_DIRECTOR_BINARY}" ]; then
      status "${BAREOS_DIRECTOR_BINARY}" "${BAREOS_DIRECTOR_PORT}"
      exit $?
    else
      echo "${BAREOS_DIRECTOR_BINARY} not executable. Did you forget to build?" >&2
      exit 1
    fi
    ;;

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

exit 0
