#!/bin/sh

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

set -eu

untrusted_agent="$QREXEC_SERVICE_ARGUMENT"

if test -z "${untrusted_agent}"; then
  echo "Agent name is empty" >&2
  exit 1
fi

if ! (echo "${untrusted_agent}" | grep -q "^[A-Za-z0-9][A-Za-z0-9_.-]\+$")
then
  die "Forbidden characters in agent name. Allowed chars: letters, numbers, hyphen, underscore and dot. It cannot begin with hyphen, underscore or dot"
fi

## Length arbitrarily set.
if test "${#untrusted_agent}" -gt 128; then
  die "Repository name is too long: ${#untrusted_agent}"
fi

agent="${untrusted_agent}"
socket="/tmp/qubes-ssh-agent/${agent}.sock"

qvm-ssh-agent add "${agent}" >/dev/null
exec socat STDIO UNIX-CLIENT:"${socket}"
