#!/usr/bin/env bash

# Uncomment for debugging purposes:
# set -eux

UNPRIVILEGED_USERNS_ENABLED=$(cat /proc/sys/kernel/unprivileged_userns_clone 2>/dev/null)
# Resolve the real install dir even when invoked through symlinks. The deb/rpm
# payload ships /usr/bin/unityhub as a RELATIVE symlink (../lib/unityhub/unityhub),
# which the previous hand-rolled readlink loop resolved against the caller's CWD
# instead of the symlink's directory — breaking `unityhub` from a terminal and the
# .desktop launcher. (It only ever worked through the fpm-era update-alternatives
# links, which were absolute.) `readlink -f` canonicalizes the whole chain; GNU
# coreutils is a given — this script only runs on Linux.
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"

# Disable the Chromium sandbox only where it cannot work: kernels without
# unprivileged user namespaces (sysctl missing or 0). Built as an array so an
# empty result contributes NO argv entry — the old quoted `$( ... && echo )`
# form always passed one argument, an empty string when userns is enabled.
LAUNCH_ARGS=()
if [[ $UNPRIVILEGED_USERNS_ENABLED == '' || $UNPRIVILEGED_USERNS_ENABLED == 0 ]]; then
  LAUNCH_ARGS+=('--no-sandbox')
fi

exec "$SCRIPT_DIR/unityhub-bin" "${LAUNCH_ARGS[@]}" "$@"
