#! /bin/sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin
export PATH

umask 022

ACTION=$1

for DIR in /etc/ldm/rc.d /usr/share/ldm/rc.d /usr/libexec/ldm/rc.d ; do
    if [ -d "$DIR" ]; then
        RCDIRS="$RCDIRS $DIR"
    fi
done

case "${ACTION}" in
    start)
        SCRIPTS="$SCRIPTS $(find -L $RCDIRS -type f -name 'S*')"
        ;;
    stop)
        SCRIPTS="$SCRIPTS $(find -L $RCDIRS -type f -name 'K*')" 
        ;;
    init)
        SCRIPTS="$SCRIPTS $(find -L $RCDIRS -type f -name 'I*')" 
        ;;
    xsession)
        SCRIPTS="$SCRIPTS $(find -L $RCDIRS -type f -name 'X*')"
        ;;
esac

export TEXTDOMAIN=ldmrc

if [ -f /usr/bin/gettext.sh ]; then
    . /usr/bin/gettext.sh
else
    eval_gettext() {
        if [ $"test" = "\$test" ]; then
            eval "echo $*"
        else
            echo $"$*"
        fi
    }
fi

for SCRIPT in ${SCRIPTS}; do
    SCRIPT_NAMES="$SCRIPT_NAMES $(basename $SCRIPT | egrep ^[0-9a-zA-Z_\-]*$)"
done

# sort scripts by order
SCRIPT_NAMES="$(echo $SCRIPT_NAMES | tr "\t " "\n" | sort -u)"

# source common functions
if [ -f "/usr/share/ltsp/ltsp-common-functions" ]; then
    . /usr/share/ltsp/ltsp-common-functions
fi

for SCRIPT in $SCRIPT_NAMES ; do
    # only source the first instance of the script found
    for DIR in $RCDIRS ; do
        if [ -f "$DIR/$SCRIPT" ]; then
            . ${DIR}/${SCRIPT}
            break
        fi
    done
done
