#!/bin/bash
#
# rc_sccl_cluster Starten oder stoppen des Script-Clusters
#
# Aufruf:
#
# rc_sccl_cluster start|stop
#
####################################################################
#

# Infos fuer RedHat:
# chkconfig: 35 95 05
# description: Start the Script-Cluster

# Infos fuer SUSE
### BEGIN INIT INFO
# Provides:       sccl2
# Required-Start: $network $named $remote_fs $syslog unix2web
# Should-Start: nfsserver
# Required-Stop:  $local_fs $network $named $remote_fs $syslog
# Should-Stop: nfsserver
#NODEB## Default-Start:  3 5
#DEB## Default-Start:  2 3 4 5
# Default-Stop:   0 1 6
# Description:    Start the Script-Cluster
### END INIT INFO
#
#
if [[ $(id -u) -ne 0 ]]; then
  echo "ERROR: not root"
  exit 1
fi 

if [[ -d /var/lock/subsys ]]; then
  lockfile=/var/lock/subsys/sccl_cluster
else
  lockfile=''
fi

if [[ -f /etc/sccl/sccl.conf ]]; then
  . /etc/sccl/sccl.conf

  if [[ -z "$LOCKDIR" ]]; then
    echo "Lockdir nicht gesetzt"
    exit 1
  fi

  case $1 in
    start)
        /etc/init.d/unix2web start /etc/unix2web/sccl.conf.service
        if [[ -f /tmp/ignore_sccl_startstop_for_update.lock ]]; then
          exit 0
        fi
        SECUPSINCE=$( echo "`date '+%s.%N'` `cat /proc/uptime`" | awk '{printf("%d", $1 - $2 + 0.5)}' )
        find "$LOCKDIR" ! -newermt "@$SECUPSINCE" -name '*_lock' -delete
        find "$LOCKDIR" ! -newermt "@$SECUPSINCE" -name '*_progress' -delete
        if [[ -f "$LOCKDIR"/node.DISABLED ]]; then
          echo "Die Clusterdienste sollen nicht gestartet werden."
        elif grep -Eq '^init |^/sbin/init' /proc/1/cmdline; then
          (touch "$LOCKDIR"/node.BOOTING; sleep ${SLEEP_AFTER_REBOOT:-60}; /usr/share/sccl/bin/sccl_start_node -r; rm -f "$LOCKDIR"/node.BOOTING)&
        else
          touch "$LOCKDIR"/node.BOOTING
          [[ $(awk '{printf("%d", $1)}' /proc/uptime) -lt 120 ]] && sleep ${SLEEP_AFTER_REBOOT:-30}
          /usr/share/sccl/bin/sccl_start_node -b -r
          rm -f "$LOCKDIR"/node.BOOTING
        fi
        [[ -z "$lockfile" ]] || touch "$lockfile"
        exit 0
        ;;
    stop)
        if [[ -f /tmp/ignore_sccl_startstop_for_update.lock ]]; then
          /etc/init.d/unix2web stop /etc/unix2web/sccl.conf.service
          exit 0
        fi
        /usr/share/sccl/bin/sccl_stop_node --clear -r
        rm -f "$LOCKDIR"/*_lock
        [[ -f "$lockfile" ]] && rm -f "$lockfile"
        exit 0
        ;;
    reload)
        /usr/share/sccl/bin/sccl_update_ips -l
        ;;
    restart)
        /etc/init.d/unix2web restart /etc/unix2web/sccl.conf.service
        ;;
    *)
        echo $0 '{start|stop|reload|restart}'
        ;;
  esac
else
  echo "Das Cluster ist nicht konfiguriert."
fi
