#!/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

# Tiling Wayland compositors place and decorate windows themselves. A declared
# desktop wins over the sockets, which a shell can keep after leaving the
# compositor. Same list as TILING_COMPOSITORS in electron/utils/linuxDisplayBackend.ts.
is_tiling_wayland() {
    [ -n "${WAYLAND_DISPLAY:-}${WAYLAND_SOCKET:-}" ] || return 1
    if [ -n "${XDG_CURRENT_DESKTOP:-}" ]; then
        case ":$(printf '%s' "$XDG_CURRENT_DESKTOP" | tr '[:upper:]' '[:lower:]'):" in
            *:hyprland:*|*:sway:*|*:niri:*|*:river:*|*:scroll:*|*:dwl:*|*:mango:*|*:miracle-wm:*|*:jay:*|*:qtile:*) return 0 ;;
        esac
        return 1
    fi
    [ -n "${HYPRLAND_INSTANCE_SIGNATURE:-}${SWAYSOCK:-}${NIRI_SOCKET:-}" ]
}

has_explicit_backend() {
    for arg in "$@"; do
        case "$arg" in --ozone-platform*) return 0 ;; esac
    done
    return 1
}

# A tiling compositor gets a native Wayland client: under XWayland the windows
# float, draw their own controls and render blurry on a scaled display.
# AGENTSROOM_NATIVE_WAYLAND=0 opts out. The IME switches keep CJK input working.
wants_wayland() {
    [ "${AGENTSROOM_NATIVE_WAYLAND:-}" = "0" ] && return 1
    is_tiling_wayland || return 1
    ! has_explicit_backend "$@"
}

# Electron 38+ opens a native Wayland window on a Wayland session. Everywhere
# else 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
    ! has_explicit_backend "$@"
}

if wants_wayland "$@"; then
    set -- --ozone-platform=wayland --enable-wayland-ime --wayland-text-input-version=3 "$@"
elif wants_x11 "$@"; then
    set -- --ozone-platform=x11 "$@"
fi

# `agentsroom --server`: AgentsRoom on a machine with no screen. Chromium picks its
# display backend before any JS runs, and the headless screen measures 1x1 px unless
# told otherwise, so these are passed here rather than by a relaunch from main.ts,
# which would make systemd lose track of the main process. Same rule as
# electron/serverMode/serverFlags.ts, an explicit --ozone-platform is respected.
wants_server() {
    server=1
    for arg in "$@"; do
        case "$arg" in
            --server) server=0 ;;
            --ozone-platform*) return 1 ;;
        esac
    done
    return $server
}

if wants_server "$@"; then
    set -- --ozone-platform=headless --ozone-override-screen-size=1600,1000 --disable-gpu "$@"
    # Chromium refuses to run as root with its sandbox on, and a VPS often hands out
    # root by default. Better a running server and a clear word than an abort.
    if [ "$(id -u)" = "0" ]; then
        echo "AgentsRoom: running as root, without the Chromium sandbox. Prefer a dedicated user: some agent CLIs refuse to run as root." >&2
        exec "$BIN" --no-sandbox "$@"
    fi
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 "$@"
