#!/bin/sh
# Launches the BTGuard VPN UI. Package postinst adds the installing user to the
# btguardvpn group, but that membership is not visible in an already-running
# desktop session until logout. Use sg(1) so a fresh install works from the app
# menu without extra steps (same pattern as the docker group on many distros).
REAL=/usr/lib/btguard-vpn/btguard-vpn

if [ "$(id -u)" -eq 0 ] || id -nG 2>/dev/null | grep -qw btguardvpn; then
	exec "$REAL" "$@"
fi

if command -v sg >/dev/null 2>&1 && getent group btguardvpn >/dev/null 2>&1; then
	cmd="exec"
	# shellcheck disable=SC2086
	set -- "$REAL" "$@"
	for arg in "$@"; do
		cmd="$cmd $(printf '%s' "$arg" | sed "s/'/'\\\\''/g; s/^/'/; s/$/'/")"
	done
	exec sg btguardvpn -c "$cmd"
fi

exec "$REAL" "$@"
