#!/bin/bash
# /usr/bin/sotavpn. Installed by build_linux_release.sh; tested by
# test/ci/linux_launcher_test.dart. GROUP and APP repeat linux/sota-connect.service
# and SotaDaemonIdentity.brandSlug.
#
# The postinst adds the installing user to the sota-connect group, but a
# running session keeps the groups it logged in with, so until the next login
# the GUI cannot open the daemon socket or write rule_sets/. When the user IS
# in the group per /etc/group while this process is not, run the app under
# `sg`, which needs no password for a member.
#
# Caveats of sg: it switches the PRIMARY gid to sota-connect (no supplementary-
# only variant exists without root), so every file the app creates in this
# session would carry that group. Hence umask 077: nothing the app writes
# (access key, logs, downloads) becomes readable or writable by other group
# members. The daemon (root, CAP_DAC_READ_SEARCH) reads rule_sets/ regardless.
# From the next login the plain path is taken and the umask is the user's own.
#
# If sg cannot work here (no_new_privs, no setuid bit, nologin shell, a group
# password prompt without a TTY) the probe fails and the app starts directly:
# connecting then needs a re-login, but the app always opens.
APP=/usr/lib/sota-connect/sotavpn
GROUP=sota-connect

if [ -z "${SOTA_LAUNCHER_DONE:-}" ] && command -v sg >/dev/null 2>&1 &&
   ! id -Gn 2>/dev/null | tr ' ' '\n' | grep -qx "$GROUP" &&
   id -Gn "$(id -un)" 2>/dev/null | tr ' ' '\n' | grep -qx "$GROUP" &&
   sg "$GROUP" -c true </dev/null >/dev/null 2>&1; then
    # sg hands one string to /bin/sh -c (dash on Debian), so every argument is
    # single-quoted by hand: bash's printf %q may emit $'…', which dash lacks.
    q="'\\''"
    cmd="umask 077; exec '${APP//\'/$q}'"
    for a in "$@"; do
        cmd="$cmd '${a//\'/$q}'"
    done
    export SOTA_LAUNCHER_DONE=1
    exec sg "$GROUP" -c "$cmd"
fi
exec "$APP" "$@"
