#!/bin/sh
#
# Restart the daemons which might have changed the configuration
# during install

set -e

cd /etc/init.d

# Workaround for apache problem.  Somethign is killing the parent
# process but leaving the kids running.  This make it impossible to
# restart apache the normal way.  This is skolelinux
# bug #636. [pere 2004-03-18]
if kill -0 `cat /var/run/apache.pid 2>/dev/null` > /dev/null 2>&1 ; then
    :
else
    echo "warning: Failed to find apache parent process.  Killing all of them."
    pkill apache
fi

echo "info: Restarting services in sequence."

for service in \
    networking \
    sysklogd \
    bind9 \
    ntpdate ntp-refclock \
    inetd \
    slapd \
    nscd \
    atd \
    dhcp3-server \
    courier-authdaemon courier-imap \
    apache \
    samba \
    squid \
    webmin \
    nfs-common nfs-kernel-server \
    autofs \
    ssh \
    mysql postgresql \
    xfs \
    nagios \
    ;
    do
  if test -x $service ; then
      echo "info: Restarting '$service'."
      # Andreas claimed that 'restart' do not work for slapd.  Use stop/start
      # instead. [pere 2002-08-28]
      ./$service stop || true
      sleep 1
      ./$service start || true
  else
      echo "warning: Not restarting '$service', as init.d script is missing."
  fi
done

# Workaround to fix skolelinux bug #286 and debian bug #156332
# Check for running dhcp
#  if running stop 
#  if still running
#   kill dhcp
#   use at to start dhcp i X minutes
#   restart at
#  else (not running)
#   start dhcp
PIDFILE=/var/run/dhcpd.pid
if [ -f $PIDFILE ] ; then 
    echo "info: OK, Found pidfile"
    PID=`cat $PIDFILE`
    if [ "$PID" ] ; then
	echo "info: OK, Found pid '$PID'"
	if ps h $PID >/dev/null ; then 
	    echo "info: OK, DHCP is running, trying to stop"
	    /etc/init.d/dhcp3-server stop
	fi  
	sleep 5
	if kill -0 "$PID" >/dev/null ; then
	    echo "info: DAMN, DHCP is still running, forcing to stop"
	    kill -9 "$PID" || true
	    echo "info: Delaying restart of DHCP"
            # Need to cd to safe dir, since working dir will be removed in soon
	    ( cd /tmp ; echo /etc/init.d/dhcp3-server start | at +1min )
	    echo "info: DHCP should be in 1 minute"
	else
	    echo "info: OK, DHCP was stopped, starting again"
	    /etc/init.d/dhcp3-server start
	fi
    else
	echo "warning: dhcpd pid file was empty.  Trying to start it."
	/etc/init.d/dhcp3-server start
    fi
fi

exit 0
