#!/bin/bash
#
# bacula-dir      This shell script takes care of starting and stopping
#                 the Bacula director service (DIR).
#
# chkconfig: - 92 09
# description:    Bacula is a network client/server based backup program.
# processname:    bacula-dir
# config:         /etc/bacula/bacula-dir.conf
# pidfile:        /var/run/bacula-dir.pid

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

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 1

# Defines
DESC="Bacula Director services"
PROG="bacula-dir"
EXEC="/usr/sbin/${PROG}"
LOCK="/var/lock/subsys/${PROG}"
PIDF="/var/run/${PROG}.pid"
CONF="/etc/bacula/${PROG}.conf"

# Include config
if [ -s /etc/sysconfig/${PROG} ]; then
  . /etc/sysconfig/${PROG}
fi

# Check for binaries and configs
[ -x ${EXEC} ] || exit 5
[ -f ${CONF} ] || exit 6

# Select correct pthreads
if [ -d "/lib/tls" -o -d "/lib64/tls" -a `uname -r | cut -c1-3` = "2.4" ]; then
  export LD_ASSUME_KERNEL=2.4.19
fi


checkcfg() {
	CONF_OK=0
	if ${EXEC} ${DIR_OPTIONS} ${OPTIONS} -t >/dev/null 2>&1; then
	  CONF_OK=1
	else
	  RETVAL=$?
	fi

	if [ ${CONF_OK} -ne 1 ]; then
	  ERR=`${EXEC} ${DIR_OPTIONS} ${OPTIONS} -t 2>&1 | sed s/\n/\\n/g`

	  if [ `tty` != "/dev/console" ]; then
	    echo -e "\n${ERR}"
	    echo -n $"Error in configuration file ${CONF}: "
	  fi

	  failure $"Error in configuration file ${CONF}: ${ERR}"
	  echo
	  exit ${RETVAL}
	fi
}

start() {
	# Start daemons.
	echo -n $"Starting ${DESC}: "
	checkcfg

	daemon ${EXEC} ${DIR_OPTIONS} ${OPTIONS}
	RETVAL=$?

	[ ${RETVAL} -eq 0 ] && touch ${LOCK}
	echo
	return ${RETVAL}
}

stop() {
	# Stop daemons.
	echo -n $"Shutting down ${DESC}: "
	killproc ${PROG}
	RETVAL=$?

	[ ${RETVAL} -eq 0 ] && rm -f ${LOCK}
	echo
	return ${RETVAL}
}

restart() {
	stop
	sleep 2
	start
}

force_reload() {
	restart
}

rh_status() {
	status ${PROG}
}

rh_status_q() {
	rh_status >/dev/null 2>&1
}


# See how we were called.
case "${1}" in
    start)
	rh_status_q && exit 0
	${1}
	;;
    stop)
	rh_status_q || exit 0
	${1}
	;;
    restart)
	${1}
	;;
    force-reload)
	force_reload
	;;
    status)
	rh_status
	;;
    condrestart|try-restart)
	rh_status_q || exit 0
	restart
	;;
    *)
	echo $"Usage: ${PROG} {start|stop|status|restart|try-restart|force-reload}"
	exit 2
esac
exit ${?}
