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

set -e 

sysvinit_restart_services () {
    echo "info: Stopping services in sequence."
    for ALL in /etc/rc1.d/K* ; do 
      if [ -h $ALL ] ; then 
        SERVICE=$(basename $(readlink $ALL))
      else
        SERVICE=$(basename $ALL)
      fi
      echo "info: Stopping $SERVICE"
      $ALL stop || /bin/true
    done

    for service in \
        slapd \
        rpcbind \
        apache \
        ;
        do
      if [ "$(pidof $service)" ] ; then
          echo "info: '$service' still running, sending HUP."
          pkill $service || /bin/true
      fi
    done

    echo "info: Checking what's still running"
    ps aux | while read LINE ; do 
      echo "info: $LINE"
    done

    for service in \
        slapd \
        rpcbind \
        apache \
        ;
        do
      if [ "$(pidof $service)" ] ; then
          echo "info: '$service' still running, sending KILL."
          pkill -9 $service || /bin/true
      fi
    done

    echo "info: Checking what's still running"
    ps aux | while read LINE ; do 
      echo "info: $LINE"
    done

    echo "Info: Restarting networking"
    /etc/init.d/networking restart || /bin/true

    echo "info: Starting services in sequence."
    for ALL in /etc/rc2.d/S* ; do 
      if [ -h $ALL ] ; then 
        SERVICE=$(basename $(readlink $ALL))
      else
        SERVICE=$(basename $ALL)
      fi
      echo "info: Starting $SERVICE"
      $ALL start || /bin/true
    done
}

systemd_restart_services () {
    systemctl daemon-reload

    systemctl restart networking.service

    for service in \
        apache2.service \
        cups.service \
        dovecot.service \
        exim4.service \
        icinga2.service \
        inetd.service \
        isc-dhcp-server.service \
        krb5-admin-server.service \
        krb5-kdc.service \
        ltsp.service \
        mariadb.service \
        munin-node.service \
        munin.service \
        nagios-nrpe-server.service \
        named.service \
        nfs-server.service \
        nmbd.service \
        nscd.service \
        nslcd.service \
        ntpsec.service \
        rsyslog.service \
        sitesummary-client.service \
        slapd.service \
        smbd.service \
        squid.service \
        sudo-ldap.service \
        tftpd-hpa.service \
        x2goserver.service \
        xrdp.service \
        xrdp-sesman.service
    do
        if systemctl is-active --quiet $service; then
            active="$active $service"
        fi
    done
    systemctl stop $active || true
    systemctl start $active
}

if [ -e /run/systemd/system/ ]; then
    systemd_restart_services
else
    sysvinit_restart_services
fi

exit 0
