#!/bin/sh
# -*- mode: sh; fill-column: 75; tab-width: 8; coding: utf-8-unix -*-

ROLE=hostvms

#[ $# -eq 0 ] && set -- Whonix-Gateway /bin/cat /proc/cmdline
[ $# -eq 0 ] && set -- Whonix-Gateway /bin/netstat -lnp4
[ $# -lt 2 ] && echo USAGE: $0 domain command arguments
. /usr/local/bin/usr_local_tput.bash || exit 3

HOST=$1
shift
CMD=$1
shift

# FixMe
if [ $# -lt 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
[ -z "$CMD" ] && CMD=/usr/sbin/qemu-ga && ARGS=-D

INFO $0 $HOST $CMD $ARGS

if ifconfig virbr1 | grep -q 10.0.2.2 ; then
    # lrwxrwxrwx 1 root root 11 Aug 26 21:58 /dev/virtio-ports/org.qemu.guest_agent.0 -> ../vport3p2
    INFO     ssh user@10.0.2.15 virbr1
    ssh user@10.0.2.15 ls -l /dev/virtio-ports/org.qemu.guest_agent.0 | \
	grep /dev/virtio-ports/org.qemu.guest_agent.0 || \
	    WARN NOT ssh ls -l /dev/virtio-ports/org.qemu.guest_agent.0
    # /usr/sbin/qemu-ga
    ssh user@10.0.2.15 ps ax | \
	grep qemu-ga || \
	    WARN NOT ssh ps  qemu-ga
fi


DBUG 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 -a -n "$pid" ] || exit 3

# DBUG 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
    DBUG $i
done
[ $i -lt $TRIES ] || \
    { 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 - || exit 8

rm -f /tmp/{Q,R}$$.out
exit 0
