#!/bin/sh

# Script that reports the status of the ns-slapd server.

. /usr/share/dirsrv/data/DSSharedLib

# Get the status of a single instance
status_instance() {
    # The first argument is the server ID.  Anything
    # after that is an argument to ns-slapd.
    SERV_ID=$1
    shift

    prefix="$DS_ROOT"

    libpath_add "$prefix$SERVER_DIR"
    libpath_add "$prefix"
    libpath_add "$prefix/usr/lib64"
    libpath_add ""
    libpath_add "$prefix"

    export LD_LIBRARY_PATH
    SHLIB_PATH=$LD_LIBRARY_PATH
    export SHLIB_PATH

    #
    # Use systemctl if available.
    #
    if [ -d "/usr/lib/systemd/system" ] && [ $(id -u) -eq 0 ];then
        /usr/bin/systemctl status dirsrv@$SERV_ID.service -l --no-pager
        rv=$?
        if [ $rv -ne 0 ]; then
            return 1
        fi
    else
        initfile=`get_init_file $initconfig_dir $SERV_ID` || { echo Instance $SERV_ID not found. ; return 255 ; }

        # source env. for this instance
        if [ -f $initfile ] ; then
            . $initfile
        else
            echo Instance $SERV_ID not found.
            return 255
        fi
    fi
    return 0
}

# source env. for all instances
[ -f /etc/sysconfig/dirsrv ] && . /etc/sysconfig/dirsrv

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

if [ -z "$initconfig_dir" ]; then
    initconfig_dir=/etc/sysconfig
fi

found=0
if [ $# -eq 0 ]; then
    # We're reporting the status of all instances.
    ret=0
    #
    # Use systemctl if available and running as root,
    #
    if [ -d "/usr/lib/systemd/system" ] && [ $(id -u) -eq 0 ];then
        /usr/bin/systemctl status dirsrv@*.service -l --no-pager
        ret=$?
        if [ $? -ne 0 ]; then
            return 1
        fi
    else
        initfiles=`get_initconfig_files $initconfig_dir` || { echo No instances found in $initconfig_dir ; exit 1 ; }
        for i in $initfiles; do
            inst=`normalize_server_id $i`
            echo Status of instance \"$inst\"
            status_instance $inst
            rv=$?
            #if one of them is successful, return 0.
            if [ $rv -ne 0 ]; then
                ret=`expr $ret + 1`
            fi
        done
    fi
    exit $ret
else
    # We're getting the status of a single instance.
    status_instance $@
    exit $?
fi
