#!/bin/sh
set -eu
base=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
# Serialize launches from any installed bundle with system identity removal.
if [ -d /etc/posrelayv-identity ]; then
    exec 6< /etc/posrelayv-identity
    flock -sn 6 || { printf '[Startup] POSRelayv identity service is being removed.\n' >&2; exit 1; }
fi
# Keep a shared lock on the bundle until Electron exits.
exec 9< "$base"
flock -sn 9 || { printf '[Startup] POSRelayv is being removed.\n' >&2; exit 1; }
case ${1:-} in
    --posrelay-cli|--posrelay-core)
        if [ "$#" -ne 1 ]; then
            printf '[Startup] Viewer launch refused reason=invalid_internal_arguments\n' >&2
            exit 1
        fi ;;
    *) if [ "$#" -gt 0 ]; then exec "$base/bin/viewer-core" launch "$@"; fi ;;
esac
# Only the core needs access to the identity sockets. Electron and its FUSE
# helper keep the desktop's primary GID so the file manager can read the mount.
if [ "${1:-}" = --posrelay-core ]; then
    if ! id -Gn | tr ' ' '\n' | grep -qx posrelayv &&
       id -Gn "$(id -un)" | tr ' ' '\n' | grep -qx posrelayv; then
        export POSRELAY_CORE_EXECUTABLE="$base/bin/viewer-core"
        if command -v sg >/dev/null 2>&1; then
            exec sg posrelayv -c 'exec "$POSRELAY_CORE_EXECUTABLE" serve'
        fi
        if command -v newgrp >/dev/null 2>&1; then
            exec newgrp posrelayv -c 'exec "$POSRELAY_CORE_EXECUTABLE" serve'
        fi
        printf '[Startup] Core launch refused reason=identity_group_tool_unavailable\n' >&2
        exit 1
    fi
    exec "$base/bin/viewer-core" serve
fi
case ${XDG_SESSION_TYPE:-} in
    wayland) backend=wayland ;;
    x11) backend=x11 ;;
    *)
        if [ -n "${WAYLAND_DISPLAY:-}" ]; then
            backend=wayland
        elif [ -n "${DISPLAY:-}" ]; then
            backend=x11
        else
            printf '[Startup] Viewer launch refused reason=desktop_session_unavailable\n' >&2
            exit 1
        fi
        ;;
esac
printf '[Startup] Desktop backend selected reason=ozone_%s\n' "$backend" >&2
exec "$base/runtime/electron" "--ozone-platform=$backend" "$@"
