#!/usr/bin/env sh
set -eu

if [ "${1:-}" = "--help" ]; then
  echo "Usage: msime-linux-settings [--panel settings|about|help|feedback|dictionary|handwriting|keyboard|emoji|clipboard|voice|cloud-dictionary|cloud-clipboard] [desktop arguments...]"
  echo "       msime-linux-settings --sync-omarchy-theme   (write the Omarchy candidate skin from the current Omarchy theme, without opening a window)"
  exit 0
fi
# --panel names a surface or one of the settings sections below; it becomes the desktop shell's --route argument. A settings section is a "settings:<category>" route, because only a surface may head a route. The input method hosts pass --route=<route> themselves, which reaches the shell through the remaining arguments.
route=
if [ "${1:-}" = "--panel" ]; then
  case "${2:-}" in
    about|help|feedback|dictionary) route=settings:$2 ;;
    settings|handwriting|keyboard|emoji|clipboard|voice|cloud-dictionary|cloud-clipboard) route=$2 ;;
    *) echo "MSIME panel name is missing or unsupported" >&2; exit 2 ;;
  esac
  shift 2
fi

if [ -n "${MSIME_CLIENT_HOST_OPTIONS:-}" ]; then
  config=$MSIME_CLIENT_HOST_OPTIONS
elif [ -n "${MSIME_IBUS_OPTIONS:-}" ]; then
  config=$MSIME_IBUS_OPTIONS
else
  config=${XDG_CONFIG_HOME:-$HOME/.config}/msime-client/runtime-options.json
  case "$config" in
    /*) ;;
    *) echo "MSIME user configuration directory must be absolute" >&2; exit 1 ;;
  esac
  # Match the IBus component's installed configuration fallback. An existing unreadable file or dangling symlink is a broken user configuration.
  if [ ! -e "$config" ] && [ ! -L "$config" ]; then
    system_config='/etc/msime-client/runtime-options.json'
    # With neither file present the window opens on its first-run page, which prepares the user file named here.
    if [ -e "$system_config" ] || [ -L "$system_config" ]; then
      config=$system_config
    fi
  fi
fi

case "$config" in
  /*) ;;
  *) echo "MSIME runtime options must be an absolute path: $config" >&2; exit 1 ;;
esac
if { [ -e "$config" ] || [ -L "$config" ]; } && [ ! -r "$config" ]; then
  echo "MSIME runtime options are not readable: $config" >&2
  exit 1
fi

launcher_path=$0
link_depth=0
while [ -L "$launcher_path" ]; do
  link_depth=$((link_depth + 1))
  [ "$link_depth" -le 32 ] || { echo "MSIME settings launcher symlink chain is too deep: $0" >&2; exit 1; }
  link=$(readlink "$launcher_path")
  case "$link" in
    /*) launcher_path=$link ;;
    *) launcher_path=$(dirname -- "$launcher_path")/$link ;;
  esac
done
launcher_dir=$(CDPATH= cd -- "$(dirname -- "$launcher_path")" && pwd)
export MSIME_CLIENT_HOST_OPTIONS=$config
# 只在加载了 NVIDIA 专有驱动内核模块（含 nvidia-open）时默认禁用 WebKit 合成与 DMA-BUF 渲染器：前者规避 NVIDIA 下的 GBM 分配失败与 Wayland 显式同步协议错误（#3273），后者规避 NVIDIA 加 KWin 时窗口一启动就以 Error 71 退出（#5834，WebKit bug 280210）。两个变量都会让 WebKit 退回非合成的 CPU 绘制，其他显卡上这条路径在 niri 下持续闪烁（#6847）、滚动整块重绘（#6403），所以不再对所有机器默认打开。
# 按内核模块判断而不看哪块显卡在渲染：#3273 的机器是 Intel 核显加 NVIDIA 独显，照样出错。模块状态对所有入口都一样，终端、桌面菜单、IBus/Fcitx5 菜单拉起的窗口因此得到同一组默认值；会话类型则不然（Fcitx5 可能早于图形会话启动），所以不按它判断。
nvidia_driver=
for nvidia_marker in /proc/driver/nvidia/version /sys/module/nvidia; do
  if [ -e "$nvidia_marker" ]; then
    nvidia_driver=1
    break
  fi
done
# 调用方显式给出的非空值一律原样保留，用于排查上游问题。空值按未设置处理：WebKit 把除 `0` 以外的任何值（包括空串）都当作禁用，原样传下去会在其他显卡上悄悄关掉合成。
if [ -n "$nvidia_driver" ]; then
  export WEBKIT_DISABLE_COMPOSITING_MODE=${WEBKIT_DISABLE_COMPOSITING_MODE:-1}
  export WEBKIT_DISABLE_DMABUF_RENDERER=${WEBKIT_DISABLE_DMABUF_RENDERER:-1}
else
  [ -n "${WEBKIT_DISABLE_COMPOSITING_MODE:-}" ] || unset WEBKIT_DISABLE_COMPOSITING_MODE
  [ -n "${WEBKIT_DISABLE_DMABUF_RENDERER:-}" ] || unset WEBKIT_DISABLE_DMABUF_RENDERER
fi
if [ -n "$route" ]; then
  exec "$launcher_dir/msime-linux-desktop" "--route=$route" "$@"
fi
exec "$launcher_dir/msime-linux-desktop" "$@"
