#!/bin/sh

torrus_config_pl='/usr/share/torrus/conf_defaults/torrus-config.pl'
torrus_initscript='/usr/share/torrus/conf_defaults/initscript.conf'
torrus_siteconfig_pl='/etc/torrus/conf/torrus-siteconfig.pl'
torrus_site_initscript='/etc/torrus/conf/initscript.siteconf'
torrus_bin='/usr/sbin/torrus'
bindir='/usr/share/torrus/bin'
piddir='/var/run/torrus'

# Set the variables and read in the configuration files
TORRUS_VERBOSE='no'
TORRUS_DAEMONS='collector monitor'
# This one must be present
. ${torrus_initscript}
test -f ${torrus_site_initscript} && . ${torrus_site_initscript}
monitor_cmdopts="${TORRUS_MONITOR_DELAY}"
collector_cmdopts="${TORRUS_COLLECTOR_CMDOPTS}"

# Check for the presence of essential configuration files and utilities
test -f "${torrus_bin}"           || exit 0
test -f "${torrus_config_pl}"     || exit 0
test -f "${torrus_siteconfig_pl}" || exit 0
for d in ${TORRUS_DAEMONS}
do
  test -x "${bindir}/${d}"        || exit 0
done

# Set up the utilities for verbose/non-verbose displays
if test "${TORRUS_VERBOSE}" = "yes"; then
  NECHO='/bin/true'
  VECHO='/bin/echo'
  SLEEP='progress_sleep'
else
  NECHO='/bin/echo'
  VECHO='/bin/true'
  SLEEP='/bin/sleep'
fi

for d in ${TORRUS_DAEMONS}; do
  eval trees_${d}=\"`/usr/bin/perl -e 'require "'$torrus_config_pl'";
  while((my $key, $val) = each %Torrus::Global::treeConfig) {
    print "$key " if $val->{run}{'${d}'};
  };'`\"
done

start_daemons () {
  for d in ${TORRUS_DAEMONS}; do
    eval trees=\"\$\{trees_${d}\}\"
    eval daemon_cmdopts=\"\$\{${d}_cmdopts\}\"
    daemon_cmdopts="${TORRUS_CMDOPTS} ${daemon_cmdopts}"
    if test -z "${trees}"; then
      echo "Not starting Torrus ${d} daemons as no configured trees found."
    else
      echo -n "Starting Torrus ${d} daemons for trees:"
      for t in ${trees}; do
        echo -n " ${t}"
        start-stop-daemon --start --quiet --chuid "Debian-torrus:Debian-torrus" \
	                  --exec "${bindir}/${d}"                               \
	                  --pidfile "${piddir}/${d}.${t}.pid"                   \
	                  -- --tree="${t}" ${daemon_cmdopts}
      done
      echo "."
    fi
  done
}

progress_sleep() {
  for i in $(seq 1 ${1})
  do
    echo -n "."
    sleep 1
  done
}

stop_daemons () {
  tokill=""
  ${NECHO} -n "Stopping Torrus daemons (this may take a while)..."
  ${VECHO} -n "Sending TERM signal to all Torrus daemons (attempt 1 of $((TORRUS_KILL_COUNT+1)))..."
  for d in ${TORRUS_DAEMONS}; do
    eval trees=\"\$\{trees_${d}\}\"
      for t in ${trees}; do
        pidfile="${piddir}/${d}.${t}.pid"
        if test -r "${pidfile}"; then
	  tokill="${tokill} t=${t};d=${d}"
#         If start-stop-daemon returns 1, then it is a stale pidfile
	  start-stop-daemon --stop --quiet --pidfile "${pidfile}" \
	                    --signal TERM > /dev/null 2>&1 ||     \
	                    rm -f "${pidfile}"
        fi
      done
  done
  ${VECHO} "done."
  killed=$(echo "${tokill}" | wc -w)
  notdead=1
  kc=${TORRUS_KILL_COUNT}
  while test $killed -gt 0 && test $kc -gt 0; do
#   echo "Sleeping for $killsleep seconds to allow processes to exit"
    ${VECHO} -n "Waiting ${TORRUS_KILL_SLEEP} seconds for Torrus daemons to exit"
    ${SLEEP} ${TORRUS_KILL_SLEEP}
    $VECHO "done."
#   echo "Checking for kill resistant processes [$kc/$killcount]"
    kc=$(($kc - 1))
    for tuple in ${tokill}; do
      eval ${tuple}
      pidfile="${piddir}/${d}.${t}.pid"
      if test -r "${pidfile}"; then
	${VECHO} -n "Sending TERM signal to Torrus ${d} for tree ${t} (attempt $((TORRUS_KILL_COUNT-kc+1)) of $((TORRUS_KILL_COUNT+1)))..."
        start-stop-daemon --stop --pidfile "${pidfile}" \
	                  --signal TERM > /dev/null 2>&1 || \
	                  rm -f "${pidfile}"
	$VECHO "done."
      else
#       echo "${d} for ${t} has stopped"
        killed=$(($killed - 1))
      fi
    done
  done

  if test $killed -gt 0; then
#   echo "  Killing Remaining Processes"
   for tuple in $tokill; do
     eval $tuple
     pidfile="${piddir}/${d}.${t}.pid"
     if test -r "${pidfile}"; then
#      echo "  Sending final kill -9 to Torrus ${d} for tree ${t}"
       ${VECHO} -n "Sending KILL signal to Torrus ${d} for tree ${t}..."
       start-stop-daemon --stop --quiet --pidfile "${pidfile}" --signal KILL
       rm -f "${pidfile}"
       ${VECHO} "done."
#         else
#           echo "${d} for ${t} has stopped"
     fi
   done
  fi
  ${VECHO} "All Torrus daemons have exited."
  ${NECHO} "done."
}

restart_apache () {
  for apachedir in apache apache-ssl apache-perl apache2
  do
    if test -L /etc/${apachedir}/conf.d/torrus-apache.conf ||
       test -L /etc/${apachedir}/conf.d/torrus-apache2.conf; then
       test -x /etc/init.d/${apachedir} && /etc/init.d/${apachedir} restart
    fi
  done
}

clear_cache () {
  if test -x /usr/sbin/torrus ; then
    /usr/sbin/torrus clearcache > /dev/null 2>&1 || true
  fi
}

case "$1" in
  start)   start_daemons
  ;;
  stop)    stop_daemons
  ;;
  restart) stop_daemons; start_daemons
  ;;
  force-reload) 
    stop_daemons
    clear_cache
    restart_apache
    start_daemons
  ;;
  *)  echo "Usage: $0 {start|stop|restart|force-reload}"
      exit 1
  ;;
esac

exit 0
