#!/bin/sh

# SPDX-FileCopyrightText: 2023 - 2024 Benjamin Grande M. S. <ben.grande.b@gmail.com>
#
# SPDX-License-Identifier: AGPL-3.0-or-later

set -eu

case "${GIT_TRACE_HELPER:-}" in
  true|1) set -x;;
esac

usage(){
  echo "Usage: ${helper} [<qube>] [<repository>]"
  echo "Note: qube defaults to '@default' and repository to the current repository"
  exit 1
}

is_git_repo(){
  if ! git rev-parse --show-toplevel >/dev/null 2>&1; then
    echo "Error: Either run from inside a git repository or provide it as an argument" >&2
    usage
  fi
}

helper="${0##*/git-}"
case "${1-}" in
  -h|--?help) usage;;
  "") authority="@default";;
  *) authority="${1}";;
esac
case "${2-}" in
  "") is_git_repo; repo="$(basename "$(git rev-parse --show-toplevel)")";;
  *) repo="${2}";;
esac

rpc="GitInit"
vendor="qusal"
default_qube="sys-git"
rpc_cmd="${vendor}.${rpc}+${repo}"

if command -v qrexec-client-vm >/dev/null; then
  exec qrexec-client-vm -tT -- "${authority}" "${rpc_cmd}"
elif command -v qrexec-client >/dev/null; then
  if test "${authority}" = "@default"; then
    authority="${default_qube}"
  fi
  exec qrexec-client -tT -d "${authority}" -- "DEFAULT:QUBESRPC ${rpc_cmd} dom0"
fi

die "Qrexec programs not found: qrexec-client-vm, qrexec-client"
