#!/bin/sh

##
# LDAP server
##

. /etc/rc.common

StartService ()
{
    ##
    # Start up LDAP server
    ##
    if [ "${LDAPSERVER:=-NO-}" = "-YES-" ]; then
        if ! pid=$(GetPID slapd); then
            ConsoleMessage "Starting LDAP server"
            if [ "${LDAPSSL:=-NO-}" = "-YES-" ]; then
                slapd -h "ldap:// ldaps:///"
			else
                slapd
            fi
        fi
    fi
    ##   
    # Start up LDAP replicator
    ##
    if [ "${LDAPREPLICATOR:=-NO-}" = "-YES-" ]; then
        if ! pid=$(GetPID slurpd); then
            ConsoleMessage "Starting LDAP replicator"
            mkdir -p /var/run/openldap-slurp/replica
            slurpd
        fi
    fi
}

StopService ()
{
    if pid=$(GetPID slapd); then
        ConsoleMessage "Stopping LDAP server"
        kill -INT "${pid}"
    else
        ConsoleMessage "LDAP server is not running."
    fi
    if pid=$(GetPID slurpd); then
        ConsoleMessage "Stopping LDAP replicator"
        kill -INT "${pid}"
    fi
}

RestartService ()
{
    tries=10
    StopService
    while [ -e /var/run/slapd.pid ] && (( tries-- > 0 )); do
        ConsoleMessage "Waiting for LDAP server to quit."
        sleep 1
    done
    if pid=$(GetPID slapd); then 
        kill -9 "${pid}"
        /bin/rm -f /var/run/slapd.pid
    fi
    while [ -e /var/run/slurpd.pid ] && (( tries-- > 0 )); do 
        ConsoleMessage "Waiting for LDAP replicator to quit."
        sleep 1 
    done
    if pid=$(GetPID slurpd); then 
        kill -9 "${pid}"
        /bin/rm -f /var/run/slurpd.pid
    fi 
    StartService
}


RunService "$1"
