#!/bin/bash

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# fqvm-exec!v0.01!Focused Qubes VM Exec
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#  _____  _____  ____  _____  _____  _____  __ __  __  __  ___
# /   __\/  _  \/    \/  _  \/  _  \/  _  \/  |  \/  \/  \/   \
# |   __||  |  |\-  -/|  _  <|  |  ||   __/|  |  |>-    -<\___/
# \_____/\__|__/ |__| \__|\_/\_____/\__/   \_____/\__/\__/<___>
# - "THE BEER-WARE LICENSE" - - - - - E N T R O P U X . N E T -
# P.E. wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some
# day, and you think this stuff is worth it, you can buy me
# a beer in return.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# P.E.!2012-12-26 v0.01
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

[ -n "$pexec_usr" ] || pexec_usr='user'
[ -n "$pexec_app" ] || pexec_app='term'

diecho()
{
  echo -E "$0: $2"
  exit $1
}

diesplay()
{
  zenity --error --title="$0" --text="$2"
  exit $1
}

depchk()
{
  while [ "${1+defined}" == 'defined' ]; do
    if which $bin &> /dev/null; then
      diecho '3' "Missing dependency ($1)."
    fi

    shift 1
  done
}

depchk pcregrep qvm-run zenity xprop


# get x11 window id of focused window
regex='(?<=^_NET_ACTIVE_WINDOW\(WINDOW\):\swindow id\s#\s)\S+'
wid="$(xprop -root | pcregrep -o "$regex")"

if [ -z "$wid" ]; then
  diesplay '1' 'Unable to find current X window ID.'
fi


# get window's qubes vm name
regex='(?<=^_QUBES_VMNAME\(STRING\)\s=\s\")[^"]+(?=")'
vm="$(xprop -id "$wid" | pcregrep -o "$regex")"

if [ -z "$vm" ]; then
  diesplay '2' "Window ($wid) is not originating from a QVM."
fi


# ask user which app to start
app="$(zenity --entry \
  --title='Start program' \
  --text="Start program in VM ($vm):" \
  --entry-text="$pexec_app"
)"

# exec it...
if ! qvm-run -q --tray -a "$vm" -u "$pexec_usr" "$app"; then
  diesplay '3' "Unable to execute application ($pexec_app) in VM ($vm)."
fi
