#!/bin/bash
# 
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1
# 
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 ("License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.zimbra.com/license
# 
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and limitations
# under the License.
# 
# The Original Code is: Zimbra Collaboration Suite Server.
# 
# The Initial Developer of the Original Code is Zimbra, Inc.
# Portions created by Zimbra are Copyright (C) 2005, 2006 Zimbra, Inc.
# All Rights Reserved.
# 
# Contributor(s):
# 
# ***** END LICENSE BLOCK *****
# 

PID=""
PIDFILE="/opt/zimbra/openldap/var/run/slapd.pid"

mkdir -p "/opt/zimbra/openldap/var/run/"

source /opt/zimbra/bin/zmshutil || exit 1
zmsetvars \
  ldap_is_master \
  ldap_url \
  ldap_master_url \
  ldap_replica_rid 

if [ x"$ldap_replica_rid" = "x" ]; then
  ldap_replica_rid=100
fi

if [ x$ldap_is_master = "xfalse" ]; then
	COOKIE="-c rid=$ldap_replica_rid"

  if [ "x$ldap_url" = "x$ldap_master_url" ]; then
    echo "ldap_url and ldap_master_url cannot be the same on an ldap replica"
    exit 1
  fi
fi

getpid()
{
	if [ -f $PIDFILE ]; then
		PID=`cat $PIDFILE`
	fi
}

checkrunning()
{
	getpid
	if [ "x$PID" = "x" ]; then
		RUNNING=0
	else
		kill -0 $PID
		if [ $? != 0 ]; then
			PID=""
			RUNNING=0
		else
			RUNNING=1
		fi
	fi
}

start()
{
	checkrunning
	if [ $RUNNING = 0 ]; then
		if [ ! -f /opt/zimbra/openldap-data/DB_CONFIG ]; then
			touch /opt/zimbra/openldap-data/DB_CONFIG
		fi 
		# Run db_recover on startup, in case of power failure. Removed for ldap 2.3
		# Our ldap url should be the first in the list in localconfig
		my_url=`echo ${ldap_url} | awk '{print $1}'`
		/opt/zimbra/libexec/zmconfigure /opt/zimbra/conf/slapd.conf.in /opt/zimbra/conf/slapd.conf
		sudo /opt/zimbra/openldap/libexec/slapd -l LOCAL0 -4 -u zimbra -h "$my_url" \
			-f /opt/zimbra/conf/slapd.conf 
		sleep 2
		getpid
		if [ "x$PID" = "x" ]; then
		  sudo /opt/zimbra/openldap/libexec/slapd -l LOCAL0 -4 -u zimbra -h "$my_url" \
			-f /opt/zimbra/conf/slapd.conf -d 1 2>&1 | egrep "failed|error"
			echo "ERROR - failed to start slapd"
			echo ""
			exit 1
		else
			echo "Started slapd: pid $PID"
		fi
	else
		echo "slapd already running: pid $PID"
		exit 1
	fi
}

stop()
{
	checkrunning
	if [ $RUNNING = 0 ]; then
		echo "slapd not running"
		exit 0
	else
		kill -TERM $PID
	fi
}

status()
{
	checkrunning
	if [ $RUNNING = 0 ]; then
		exit 1
	else
		echo "slapd running pid: $PID"
		exit 0
	fi
}

case "$1" in 
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		status
		;;
	*)
		echo "Usage: $0 start|stop|status"
		exit 1
		;;
esac
