#!/bin/sh

mkfifo /tmp/qrexec-rpc-stderr.$$
logger -t "$1-$2" -f /tmp/qrexec-rpc-stderr.$$ >/dev/null 2>&1 </dev/null &
exec 2>/tmp/qrexec-rpc-stderr.$$
rm -f /tmp/qrexec-rpc-stderr.$$

QUBES_RPC=/etc/qubes-rpc
# XXX: Backward compatibility
DEPRECATED_QUBES_RPC=/etc/qubes_rpc
if ! [ $# = 2 ] ; then
	echo $0: bad argument count, usage: $0 SERVICE-NAME REMOTE-DOMAIN-NAME >&2
	exit 1
fi
export QREXEC_REMOTE_DOMAIN="$2"

if [ -s "$QUBES_RPC/$1" ]; then
    CFG_FILE=$QUBES_RPC/"$1"
elif [ -s "$DEPRECATED_QUBES_RPC/$1" ]; then
    echo "$0: RPC service '$1' uses deprecated directory, please move to $QUBES_RPC" >&2
    CFG_FILE=$DEPRECATED_QUBES_RPC/"$1"
else
    echo "$0: Cannot find service $1 file in $QUBES_RPC" >&2
    exit 1
fi

if [ -x "$CFG_FILE" ] ; then
	exec "$CFG_FILE"
	echo "$0: failed to execute handler for" "$1" >&2
	exit 1
else
	exec /bin/sh "$CFG_FILE"
	echo "$0: failed to execute handler for" "$1" >&2
	exit 1
fi
