#!/bin/bash

ROLE=proxy

#[ $# -eq 0 ] && set --  Whonix-Gateway /bin/cat /proc/cmdline
[ $# -lt 2 ] && echo USAGE: $0 domain command arguments

HOST=$1
shift
CMD=$1
shift
# FixMe
if [ $? -gt 1 ]  ; then
    ARGS=""
  elif [ $? -gt 1 ] ; then
    ARGS=`sed -e 's/ /","/g' <<< $@`
  else
    ARGS="$1"
fi

[ "$HOST" = WWork106 ] && HOST=Whonix-Workstation || true
[ "$HOST" = WGate106 ] && HOST=Whonix-Gateway || true

echo INFO: $0 $HOST $CMD $ARGS

false && echo DEBUG: virsh qemu-agent-command $HOST \
  '{"execute":"guest-exec", "arguments": {"capture-output": true,"path":"'$CMD'","arg":["'$ARGS'"]}}'
virsh qemu-agent-command $HOST \
  '{"execute":"guest-exec", "arguments": {"capture-output": true,"path":"'$CMD'","arg":["'$ARGS'"]}}' \
  >/tmp/Q$$.out || exit 1$?

grep -q return /tmp/Q$$.out || exit 2
pid=`sed -e 's/.*://' -e 's/}.*//' /tmp/Q$$.out`
[ $? -eq 0 ] || exit 3

# echo DEBUG: virsh qemu-agent-command $HOST \
#  '{"execute":"guest-exec-status", "arguments": {"pid": '$pid'}}'
virsh qemu-agent-command $HOST \
  '{"execute":"guest-exec-status", "arguments": {"pid": '$pid'}}' \
  >/tmp/R$$.out || exit 4$?

TRIES=10
i=0
while [ $i -lt $TRIES ] ; do
    i=`expr $i + 1`
    virsh qemu-agent-command $HOST \
	  '{"execute":"guest-exec-status", "arguments": {"pid": '$pid'}}' \
	  >/tmp/R$$.out || exit 4$i$?
    grep -q '"exitcode":0' /tmp/R$$.out && break
    sleep 5
    echo DEBUG: $i
done
[ $i -lt $TRIES ] || \
    { echo ERROR: $i no exitcode in  /tmp/R$$.out; exit 5 ; }

b64=`sed -e 's/{"return":{"exitcode":0,"out-data":"//' -e 's/",".*//' /tmp/R$$.out`
[ $? -eq 0 ] || exit 6
[ -n "$b64" ] || exit 7

echo $b64 | base64 -d -
rm -f /tmp/{Q,R}$$.out
exit 0
