#!/usr/bin/env bash
set -euo pipefail

app=/opt/mantaray/mantaray
group=mantaray-vpn

# Package installation adds the desktop account to `mantaray-vpn`, but an
# already-running graphical login session does not gain the supplementary
# group until the next login. `sg` starts the app with the current membership
# from /etc/group, so a freshly installed desktop build works immediately.
group_id="$(getent group "$group" | cut -d: -f3)"
if [[ -z "$group_id" ]]; then
  echo "MantaRay service group is missing; reinstall the package" >&2
  exit 1
fi

if [[ "$(id -u)" -eq 0 || " $(id -G) " == *" $group_id "* ]]; then
  exec "$app" "$@"
fi

account="$(id -un)"
members="$(getent group "$group" | cut -d: -f4)"
if [[ ",$members," != *",$account,"* ]]; then
  echo "User $account is not allowed to control the MantaRay service; reinstall the package as that user" >&2
  exit 1
fi

printf -v command '%q ' "$app" "$@"
exec /usr/bin/sg "$group" -c "exec $command"
