#!/bin/sh
#
### BEGIN INIT INFO
# Provides:          fliwi-ha-only-one-running
# Should-Start:
# Required-Start:    $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Provides the ha-check 'only-one-running' for Fliwi
# Description:       This provides the ha-check 'only-one-running' executed by
#                    every host in Fliwi. This check ensures that a
#                    service runs only on one host the same time.
### END INIT INFO
set -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin
HA_ENABLED_FILE=/var/run/fliwi-ha-only-one-running/enabled

if [ -r /etc/default/locale ]; then
  . /etc/default/locale
  export LANG LANGUAGE
fi

. /lib/lsb/init-functions

case "$1" in
  start)
    log_daemon_msg "Activating ha-only-one-running for Fliwi" "fliwi-ha-only-one-running"
    if [ ! -d "$(dirname $HA_ENABLED_FILE)" ]; then
      mkdir $(dirname $HA_ENABLED_FILE)
    fi
    date +%s > $HA_ENABLED_FILE
    log_end_msg $?
  ;;
  stop)
    return_status=0
    log_daemon_msg "Disabling ha-ony-one-running for Fliwi" "fliwi-ha-only-one-running"
    set +e
    if [ -f "$HA_ENABLED_FILE" ]; then
      rm -f $HA_ENABLED_FILE || return_status=1
    fi
    set -e
    log_end_msg $return_status
  ;;
  status)
    if [ -f "$HA_ENABLED_FILE" ]; then
      log_success_msg "fliwi-ha-only-one-running is enabled"
      exit 0
    else
      log_success_msg "fliwi-ha-only-one-running is disabled"
      exit 1
    fi
  ;;
  restart|force-reload|reload)
        $0 stop
        sleep 2
        $0 start
  ;;
  *)
        echo "Usage: /etc/init.d/fliwi-ha-only-one-running {start|stop|restart|reload|force-reload|status}"
        exit 1
  ;;
esac

exit 0
