#!/usr/bin/env bash
#
# Copyright (C) 2003 VA Linux Systems Japan, K.K.
#
# LICENSE NOTICE
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#

#
# $Id: ldap,v 1.7 2004/10/13 03:20:15 taru Exp $
#

set -e

eval `ultrapossum-config init`
trap "/bin/rm -f $FAILOVER_RECOVERY_PIDFILE; eval `ultrapossum-config term`" 0

# Source function library.
source_shell $HA_DIR/shellfuncs

ldap_start () {
  echo $$ > $FAILOVER_RECOVERY_PIDFILE
  if test "x`$MODULEDIR/server/startup master_status`" = "xstopped"; then
    ha_log "info: $0: Starting"

    # recovery 
    if test "x$NFSDIR" != "x" && ! include "$BACKUP" "$SYNCBACKUPS"; then
      $MODULEDIR/failover/recovery
    fi

    # running master service
    if ! $MODULEDIR/server/startup master_start; then
      ha_log "Info: $0: Master can't be started"
    fi
  else
    ha_log "info: $0: Master already running"
  fi
  /bin/rm -f $FAILOVER_RECOVERY_PIDFILE
}

ldap_stop () {
    ha_log "info: $0: Shutting down"
    $MODULEDIR/server/startup master_stop
    if test "x$HOST" = "x$BACKUP"; then
      if test "x`$MODULEDIR/server/startup slave_status`" = "xstopped"; then
        ha_log "starting slave slapd"
        ldapslave_start
      fi
    fi
}

# See how we were called.
case "$1" in
  start)
        ldap_start
        ;;
  stop)
        ldap_stop
        ;;
  restart)
        ldap_stop
        ldap_start
        ;;
  status)
        $MODULEDIR/server/startup master_status
        ;;
  *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
esac
exit 0
