#! /bin/sh
#
# Copyright (C) 2000-2015 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
# 
# bacula  This shell script takes care of starting and stopping
#	  the bacula Director daemon on Debian/Ubuntu/Kubuntu 
#	  systems. 
#
#   Kern E. Sibbald - 21 March 2008
#
#  For Bacula release 9.0.0 (02 July 2017) -- ubuntu
#
### BEGIN INIT INFO
# Provides:	     bacula-sd
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start Bacula Storage daemon at boot time
# Description:	     Enable Bacula Storage daemon.
### END INIT INFO


NAME="bacula-sd"
DESC="Bacula Storage Daemon"
DAEMON=/opt/bacula/bin/${NAME}
BUSER=bacula
BGROUP=tape
BOPTIONS="-c /opt/bacula/etc/${NAME}.conf"
BPORT=9103

PATH=/sbin:/bin:/usr/sbin:/usr/bin

test -f $DAEMON || exit 0

if [ -n "`getent services ${NAME}`" ]; then
   BPORT=`getent services ${NAME} | awk '{ gsub("/tcp","",$2); print $2; }'`
fi

if [ -f /etc/default/$NAME ]; then
   . /etc/default/$NAME
fi

PIDFILE=/opt/bacula/working/${NAME}.${BPORT}.pid

if [ "x${BUSER}" != "x" ]; then
   USERGRP="--chuid ${BUSER}"
   if [ "x${BGROUP}" != "x" ]; then
      USERGRP="${USERGRP}:${BGROUP}"
   fi
fi

RETVAL=0
case "$1" in
   start)
      echo -n "Starting ${DESC}: "
      start-stop-daemon --start --quiet --pidfile ${PIDFILE} ${USERGRP} --exec ${DAEMON} -- ${BOPTIONS}
      RETVAL=$?
      echo "${NAME}"
      ;;
   stop)
      echo -n "Stopping ${DESC}: "
      start-stop-daemon --oknodo --stop --quiet ${USERGRP}  --exec ${DAEMON} -- ${BOPTIONS}
      RETVAL=$?
      echo "${NAME}"
      ;;
   restart|force-reload)
      $0 stop
      sleep 5
      $0 start
      RETVAL=$?
      ;;
   *)
      echo "Usage: /etc/init.d/${NAME} {start|stop|restart|force-reload}" >&2
      exit 1
      ;;
esac
exit $RETVAL
