#!/bin/bash
# omarchy:summary=Set the input method toggle key, migrating the menu key if needed
# omarchy:args=<ctrl-space|super-space>
# omarchy:examples=omarchycn ime hotkey ctrl-space | omarchycn ime hotkey super-space

set -euo pipefail

choice="${1:?usage: omarchycn ime hotkey <ctrl-space|super-space>}"
fcitx_config="$HOME/.config/fcitx5/config"
bindings="$HOME/.config/hypr/bindings.lua"

# Replace or append the [Hotkey/TriggerKeys] section in fcitx5 global config
set_trigger() {
  local key="$1"

  mkdir -p "${fcitx_config%/*}"
  touch "$fcitx_config"
  awk '
    /^\[Hotkey\/TriggerKeys\]$/ { skip = 1; next }
    /^\[/ { skip = 0 }
    !skip { print }
  ' "$fcitx_config" > "$fcitx_config.omarchycn-tmp"
  printf '[Hotkey/TriggerKeys]\n0=%s\n' "$key" >> "$fcitx_config.omarchycn-tmp"
  mv "$fcitx_config.omarchycn-tmp" "$fcitx_config"
}

remove_menu_migration() {
  if [[ -f $bindings ]]; then
    sed -i '/^-- OmarchyCN ime hotkey begin$/,/^-- OmarchyCN ime hotkey end$/d' "$bindings"
  fi
}

case "$choice" in
ctrl-space)
  set_trigger "Control+space"
  remove_menu_migration
  echo "输入法切换键: Ctrl+Space（Omarchy 菜单保持 Super+Space）"
  ;;
super-space)
  set_trigger "Super+space"
  mkdir -p "${bindings%/*}"
  touch "$bindings"
  remove_menu_migration
  cat >> "$bindings" <<'EOF'
-- OmarchyCN ime hotkey begin
hl.unbind("SUPER + SPACE")
hl.unbind("SUPER + ALT + SPACE")
o.bind("SUPER + ALT + SPACE", "Omarchy menu", "omarchy-menu toggle")
-- OmarchyCN ime hotkey end
EOF
  echo "输入法切换键: Super+Space"
  echo "Omarchy 菜单已迁移至 Super+Alt+Space（写入 $bindings）"
  echo "原 Super+Alt+Space 的 Apps 菜单让位，可从根菜单进入或自行改绑"
  ;;
*)
  echo "Unknown hotkey choice: $choice (expected ctrl-space or super-space)" >&2
  exit 1
  ;;
esac

if systemctl --user is-active omarchy-fcitx5.service > /dev/null 2>&1; then
  systemctl --user restart omarchy-fcitx5.service
fi
