#!/bin/sh
# Generated during packaging. Chromium only honours --no-sandbox when it is
# present on the real command line, so the decision happens here.
set -eu

launcher_path="$0"

case "$launcher_path" in
  */*) ;;
  *) launcher_path="$(command -v -- "$launcher_path" 2>/dev/null || printf '%s' "$launcher_path")" ;;
esac

launcher_path="$(readlink -f -- "$launcher_path" 2>/dev/null || printf '%s' "$launcher_path")"
binary_path="$(dirname -- "$launcher_path")/toju-bin"

read_kernel_flag() {
  if [ ! -r "$1" ]; then
    printf '%s' "$2"
    return 0
  fi

  cat -- "$1" 2>/dev/null || printf '%s' "$2"
}

sandbox_is_blocked() {
  if [ "$(read_kernel_flag /proc/sys/kernel/apparmor_restrict_unprivileged_userns 0)" = "1" ]; then
    return 0
  fi

  if [ "$(read_kernel_flag /proc/sys/kernel/unprivileged_userns_clone 1)" = "0" ]; then
    return 0
  fi

  if [ "$(read_kernel_flag /proc/sys/user/max_user_namespaces 1)" = "0" ]; then
    return 0
  fi

  return 1
}

for launcher_arg in "$@"; do
  case "$launcher_arg" in
    --no-sandbox) exec "$binary_path" "$@" ;;
  esac
done

if sandbox_is_blocked; then
  exec "$binary_path" --no-sandbox "$@"
fi

exec "$binary_path" "$@"
