#!/bin/bash

# Copyright (C) 2021 Elliot Killick <elliotkillick@zohomail.eu>
# Licensed under the MIT License. See LICENSE file for details.

[ "$DEBUG" == 1 ] && set -x
set -u -e

set -E # Enable function inheritance of traps
trap exit ERR
unset GETOPT_COMPATIBLE
name=${0##*/}

usage() {
    echo "Usage: $name [--instance-arg=...] [--resolution=[WIDTHxHEIGHTxFPS]] [--] webcam|screenshare [destination qube]" >&2
    echo "Resolution example: 1920x1080x60"
    echo "--instance-arg is used internally when started via systemd"
    exit "$1"
}

resolution=
instance_arg=
opts=$(getopt "--name=$name" --longoptions=resolution:,help,instance-arg: -- r: "$@") || exit
eval "set -- $opts"
while :; do
    case $1 in
        -r|--resolution)
            if [[ -z "$2" ]]; then
                echo "$name: Empty resolution argument" >&2
                usage 1
            fi
            resolution=${2//@/+}
            resolution=${resolution//x/+}
            shift 2
            ;;
        --instance-arg)
            if [[ -z "$2" ]]; then
                echo "$name: missing instance arg value" >&2
                usage 1 >&2
            fi
            instance_arg="${2//\\x2b/+}"
            shift 2
            ;;
        -h|--help) usage 0;;
        --) shift; break;;
        *) exit 1;; # cannot happen
    esac
done

if [ "$#" -gt 2 ] || [ "$#" -lt 1 ]; then usage 1 >&2; fi

video_source="$1" qube=${2-'@default'}

if [[ "$qube" != "@default" ]] && [[ -n "$instance_arg" ]]; then
    echo "Cannot use --instance-arg together with destination qube" >&2
    exit 1
fi

if [[ -n "$instance_arg" ]]; then
    qube="${instance_arg%%+*}"
    # in reality full qrexec arg
    resolution="${instance_arg#*+}"
fi

case "$video_source" in
    webcam)
        qvc_service="qvc.Webcam"
        ;;
    screenshare)
        qvc_service="qvc.ScreenShare"
        ;;
    *)
        usage 1
        ;;
esac

exit_clean () {
    exit_code="$?"

    /usr/share/qubes-video-companion/receiver/destroy.py "$dev_path"

    if [ "$video_source" = "webcam" ] && [ "$exit_code" = "141" ]; then
        echo "The webcam device is in use! Please stop any instance of Qubes Video Companion running on another qube." >&2
        exit 1
    fi

    exit "$exit_code"
}

dev_path=$(/usr/share/qubes-video-companion/receiver/setup.py "$video_source")
trap exit_clean EXIT
# Filter standard error escape characters for safe printing to the terminal from the video sender
qrexec-client-vm --filter-escape-chars-stderr -- "$qube" "$qvc_service+$resolution" /usr/share/qubes-video-companion/receiver/receiver.py "$dev_path"
