#!/bin/sh

# Script that stops the ns-slapd server.
# Exit status can be:
#       0: Server stopped successfully
#       1: Server could not be stopped
#       2: Server was not running

. /usr/share/dirsrv/data/DSSharedLib

RUN_DIR="/run/dirsrv";

stop_instance() {
    SERV_ID=$1

    PIDFILE=/var$RUN_DIR/slapd-$SERV_ID.pid
    if test ! -f $PIDFILE ; then
        echo No ns-slapd PID file found. Server is probably not running
        return 2
    fi
    PID=`cat $PIDFILE`

    #
    # use systemctl if running as root
    #
    if [ -d "/usr/lib/systemd/system" ] && [ $(id -u) -eq 0 ];then
        # 
        # Now, check if systemctl is aware of this running instance
        #
        /usr/bin/systemctl is-active dirsrv@$SERV_ID.service > /dev/null 2>&1
        if [ $? -eq 0 ]; then
            # 
            # systemctl sees the running process, so stop it correctly
            #
            /usr/bin/systemctl stop dirsrv@$SERV_ID.service -l
        else
            # 
            # Have to kill it since systemctl doesn't think it's running
            #
            kill $PID
        fi
    else
        instance=`get_slapd_instance /etc/dirsrv $SERV_ID` || { echo Instance $SERV_ID not found. ; return 1 ; }

        # see if the server is already stopped
        kill -s 0 $PID > /dev/null 2>&1 || {
            echo Server not running
            if test -f $PIDFILE ; then
                rm -f $PIDFILE
            fi
            return 2
        }
        # server is running - kill it
        kill $PID
    fi
    
    # wait for 10 minutes (600 times 1 second)
    loop_counter=1
    max_count=600
    while test $loop_counter -le $max_count; do
        loop_counter=`expr $loop_counter + 1`
        if kill -s 0 $PID > /dev/null 2>&1 ; then
            sleep 1;
        else
            if test -f $PIDFILE ; then
                rm -f $PIDFILE
            fi
            return 0
        fi
    done
    if test -f $PIDFILE ; then
        echo Server still running!! Failed to stop the ns-slapd process: $PID.  Please check the errors log for problems.
    fi
    return 1
}

while getopts "d:" flag
do
    case "$flag" in
        d) initconfig_dir="$OPTARG";;
    esac
done
shift $(($OPTIND-1))

if [ $# -eq 0 ]; then
    # We're stopping all instances.
    ret=0
    instances=`get_slapd_instances /etc/dirsrv` || { echo No instances found in /etc/dirsrv ; exit 1 ; }
    for i in $instances; do
        if [ ! -d "$i" ] ; then
            echo No instances found in /etc/dirsrv
            exit 1
        fi
        inst=`normalize_server_id $i`
        echo Stopping instance \"$inst\"
        stop_instance $inst
        rv=$?
        if [ $rv -ne 0 ]; then
            ret=$rv
        fi
    done
    exit $ret
else
    # We're stopping a single instance.
    stop_instance $@
    exit $?
fi
