#!/usr/bin/sh -l
# we don't use globbing, disable it
set -f

if [ -z "${QREXEC_SERVICE_PATH+x}" ]; then
    QREXEC_SERVICE_PATH=/usr/local/etc/qubes-rpc:/etc/qubes-rpc
fi
tmpdir=${XDG_RUNTIME_DIR-/tmp}

# write stderr to both calling party and local log; be very careful about
# closing file descriptors here - if either stdout or stderr will not be closed
# when service process does the same - service call will hang (waiting for EOF
# on stdout/stderr)
stderr_pipe=$tmpdir/qrexec-rpc-stderr.$$
mkfifo -- "$stderr_pipe"
# tee can't write to file descriptor, nor /proc/self/fd/2 (EXIO on open)
return_stderr_pipe=$tmpdir/qrexec-rpc-stderr-return.$$
mkfifo -- "$return_stderr_pipe"
{ cat <"$return_stderr_pipe" >&2 2>/dev/null; rm -f -- "$return_stderr_pipe"; } </dev/null >/dev/null &
{ tee -- "$return_stderr_pipe" <"$stderr_pipe" |
       logger -t "$1-$2"; rm -f -- "$stderr_pipe"; } </dev/null >/dev/null 2>&1 &
exec 2>"$stderr_pipe"

if ! [ $# = 2 -o $# = 4 ] ; then
	echo "$0: bad argument count, usage: $0 SERVICE-NAME REMOTE-DOMAIN-NAME [REQUESTED_TARGET_TYPE REQUESTED_TARGET]" >&2
	exit 1
fi
# Avoid inheriting these from the environment
unset QREXEC_REQUESTED_TARGET QREXEC_REQUESTED_TARGET_KEYWORD QREXEC_SERVICE_ARGUMENT
export QREXEC_REQUESTED_TARGET_TYPE="$3"
if [ "$QREXEC_REQUESTED_TARGET_TYPE" = "name" ]; then
    export QREXEC_REQUESTED_TARGET="$4"
elif [ "$QREXEC_REQUESTED_TARGET_TYPE" = "keyword" ]; then
    export QREXEC_REQUESTED_TARGET_KEYWORD="$4"
fi
# else: requested target type unknown or not given, ignore
export QREXEC_REMOTE_DOMAIN="$2"
export QREXEC_SERVICE_FULL_NAME="$1"
SERVICE_WITHOUT_ARGUMENT="${1%%+*}"
if [ "${QREXEC_SERVICE_FULL_NAME}" != "${SERVICE_WITHOUT_ARGUMENT}" ]; then
    export QREXEC_SERVICE_ARGUMENT="${QREXEC_SERVICE_FULL_NAME#*+}"
else
    # Search for qubes.Service+ if given qubes.Service
    set -- "$1+" "$2"
fi


ifs=$IFS
IFS=:
for DIR in $QREXEC_SERVICE_PATH; do
    CFG_FILE="$DIR/$1"
    if [ -s "$CFG_FILE" ]; then
        break
    fi
    CFG_FILE="$DIR/$SERVICE_WITHOUT_ARGUMENT"
    if [ -s "$CFG_FILE" ]; then
        break
    fi
done
IFS=$ifs

exec "$CFG_FILE" ${QREXEC_SERVICE_ARGUMENT:+"$QREXEC_SERVICE_ARGUMENT"}
echo "$0: failed to execute handler for $1" >&2
exit 1
