#!/bin/sh

#
# CONFIG VARIABLES
##################
HELPERPATH=/usr/lib/send_infra

#
# FUNCTION DEFINITION
#####################
echoerror () {
    echo "$@" >&2
}

help() {
    echo ""
    echo "Syntax: ${0##*/} [-w|--wait|-h|--help] <function> <args>"
    echo ""
    echo "-w|--wait	wait for the function to be processed before returning."
    echo "-h|--help	display this help."
    echo ""
    echo "The different functions are:"
    export HELPPREFIX="    "
    for helper in $HELPERPATH/*; do
    	[ -x $helper ] && $helper -h
    done
    [[ ! -x $helper ]] && echo "${HELPPREFIX}none"
    echo ""
}

############
### MAIN ###
############

: "PROCESSING COMMAND LINE"
unset WAIT
RET=0

[[ $# -eq 0 ]] && RET=1 && set -- -h

case "$1" in 
    -h|--help) : "help"
        help
        exit $RET
    ;;
    -w|--wait) : "will wait"
        WAIT=1
        shift
    ;;
esac

    
[[ ! -f /var/run/dbus-session.pid ]] && exit 1
[[ ! -d /proc/$(cat /var/run/dbus-session.pid) ]] && exit 1

helper=$1; shift

if [ -x $HELPERPATH/$helper ]; then
    : "=========================================================== JUMPING TO $helper"
    debug=${-//[^x]}
    ${debug:+sh -x }$HELPERPATH/$helper ${WAIT:+-w }"$@"
    RET=$?
else
    echoerror "The function '$helper' is not defined."
    RET=1
fi

exit $RET
