#!/bin/sh
# ---------------------------------------------------------------------------
#  AgentsRoom launcher (Linux) - Chromium sandbox fallback
#
#  Chromium hard-aborts before any JS runs when the shipped chrome-sandbox
#  helper is present but not "root-owned + mode 4755":
#
#    FATAL:setuid_sandbox_host.cc(163)] The SUID sandbox helper binary was
#    found, but is not configured correctly. Rather than run without
#    sandboxing I'm aborting now.
#
#  That happens on any install where the setuid bit cannot be trusted:
#  a .deb unpacked with `dpkg -x` (no postinst), a tarball copied into /opt,
#  /opt mounted nosuid, an install done without root, or a postinst that
#  guessed wrong about unprivileged user namespaces.
#
#  The app must never abort with no window and no message, so we downgrade the
#  sandbox layer instead of failing, keeping the strongest one still available:
#    helper usable              -> launch untouched          (SUID sandbox)
#    helper broken + userns     -> --disable-setuid-sandbox  (namespace sandbox)
#    helper broken, no userns   -> --no-sandbox              (last resort)
# ---------------------------------------------------------------------------

set -u

SELF=$(readlink -f "$0" 2>/dev/null || echo "$0")
APP_DIR=$(dirname "$SELF")
BIN="$APP_DIR/agentsroom"
SANDBOX_HELPER="$APP_DIR/chrome-sandbox"

# The setuid bit is inert on a nosuid mount: Chromium's stat() check passes,
# then the helper it execs is not root and the launch fails anyway.
mount_allows_suid() {
    [ -r /proc/self/mountinfo ] || return 0
    awk -v path="$1" '
        {
            mp = $5; opts = $6
            if (index(path, mp) != 1) next
            tail = substr(path, length(mp) + 1)
            if (mp != "/" && tail != "" && substr(tail, 1, 1) != "/") next
            if (length(mp) >= best) { best = length(mp); found = opts }
        }
        END { exit (found ~ /(^|,)nosuid(,|$)/) ? 1 : 0 }
    ' /proc/self/mountinfo
}

# "Safe" also covers the absent helper: Chromium then falls back on its own.
sandbox_helper_is_safe() {
    [ -e "$SANDBOX_HELPER" ] || return 0
    [ -u "$SANDBOX_HELPER" ] && [ -x "$SANDBOX_HELPER" ] || return 1
    [ "$(stat -c %u "$SANDBOX_HELPER" 2>/dev/null)" = "0" ] || return 1
    mount_allows_suid "$SANDBOX_HELPER" || return 1
    return 0
}

# Tested as the invoking user on purpose: root is exempt from the AppArmor
# restriction that blocks unprivileged user namespaces on Ubuntu 24.04+.
userns_available() {
    [ -e /proc/self/ns/user ] || return 1
    if [ -r /proc/sys/user/max_user_namespaces ]; then
        max=$(cat /proc/sys/user/max_user_namespaces 2>/dev/null || echo 0)
        [ "${max:-0}" -gt 0 ] 2>/dev/null || return 1
    fi
    if command -v unshare >/dev/null 2>&1; then
        unshare --user true >/dev/null 2>&1 || return 1
    fi
    return 0
}

if [ ! -x "$BIN" ]; then
    echo "AgentsRoom: executable not found at $BIN" >&2
    exit 1
fi

# Electron 38+ opens a native Wayland window on a Wayland session. AgentsRoom
# keeps running through XWayland, as it did up to Electron 33: global shortcuts
# and window placement do not work for native Wayland clients. Only when an X
# server is reachable, never over an explicit --ozone-platform, and
# AGENTSROOM_NATIVE_WAYLAND=1 opts out. Same rule as electron/utils/linuxDisplayBackend.ts
# (which relaunches the AppImage and other starts that bypass this script).
wants_x11() {
    [ "${XDG_SESSION_TYPE:-}" = "wayland" ] || return 1
    [ -n "${DISPLAY:-}" ] || return 1
    [ "${AGENTSROOM_NATIVE_WAYLAND:-}" = "1" ] && return 1
    for arg in "$@"; do
        case "$arg" in --ozone-platform*) return 1 ;; esac
    done
    return 0
}

if wants_x11 "$@"; then
    set -- --ozone-platform=x11 "$@"
fi

if sandbox_helper_is_safe; then
    exec "$BIN" "$@"
fi

if userns_available; then
    echo "AgentsRoom: $SANDBOX_HELPER is not root-owned with mode 4755, falling back to the user namespace sandbox." >&2
    exec "$BIN" --disable-setuid-sandbox "$@"
fi

echo "AgentsRoom: $SANDBOX_HELPER is unusable and user namespaces are unavailable, starting without the Chromium sandbox." >&2
exec "$BIN" --no-sandbox "$@"
