#! /bin/sh
#
# bareos       This shell script takes care of starting and stopping
#	       the bareos Director daemon
#
# chkconfig: 2345 92 9
# description: Backup Archiving REcovery Open Sourced.
#
#  For Bareos release 16.2.5 (03 March 2017) -- redhat
#

# Source function library
. /etc/rc.d/init.d/functions

DIR_USER=bareos
DIR_GROUP=bareos
DIR_OPTIONS=''
OS=`uname -s`

# if /lib/tls exists, force Bareos to use the glibc pthreads instead
if [ -d "/lib/tls" -a $OS = "Linux" -a `uname -r | cut -c1-3` = "2.4" ] ; then
     export LD_ASSUME_KERNEL=2.4.19
fi

# pull in any user defined DIR_DIR_OPTIONS, DIR_USER, or DIR_GROUP
[ -f /etc/sysconfig/bareos ] && . /etc/sysconfig/bareos

#
# Disable Glibc malloc checks, it doesn't help and it keeps from getting
#   good dumps
MALLOC_CHECK_=0
export MALLOC_CHECK_

function checkcfg () {
   echo "Checking Configuration and Database connection ... "
   su -s /bin/sh ${DIR_USER} -c "/usr/sbin/bareos-dir -f -t"
   if [ $? -eq 0 ]; then
      return 0
   else
      return 1
   fi
}

RETVAL=0
case "$1" in
    start)
       checkcfg
       if [ $? -eq 0 ]; then
          if [ "${DIR_GROUP}" != '' ]; then
             DIR_OPTIONS="${DIR_OPTIONS} -g ${DIR_GROUP}"
          fi
          echo -n "Starting Bareos Director services: "
          daemon --user ${DIR_USER} /usr/sbin/bareos-dir $2 ${DIR_OPTIONS}
          RETVAL=$?
          echo
          [ $RETVAL -eq 0 ] && touch /var/lock/subsys/bareos-dir
       else
          echo "Configuration check failed, please check log file for errors"
       fi
       ;;
    stop)
       echo -n "Stopping Bareos Director services: "
       killproc /usr/sbin/bareos-dir
       RETVAL=$?
       echo
       [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/bareos-dir
       ;;
    restart)
       $0 stop
       sleep 5
       $0 start
       ;;
    status)
       status /usr/sbin/bareos-dir
       RETVAL=$?
       ;;
    *)
       echo "Usage: $0 {start|stop|restart|status}"
       exit 1
       ;;
esac
exit $RETVAL
