#!/bin/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
# 默认禁用 WebKit 合成，规避部分驱动的 GBM 分配失败与 Wayland 显式同步协议错误；保留显式覆盖以便排查。
export WEBKIT_DISABLE_COMPOSITING_MODE=${WEBKIT_DISABLE_COMPOSITING_MODE:-1}
if [ -n "$route" ]; then
  exec "$launcher_dir/msime-linux-desktop" "--route=$route" "$@"
fi
exec "$launcher_dir/msime-linux-desktop" "$@"
