#!/bin/bash

# blob:summary=Regenerate docs/keybinds.md from the Hyprland Lua bindings
# blob:hidden=true

set -e

bin_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_dir="$(dirname "$bin_dir")"
output="$repo_dir/docs/keybinds.md"

# o.bind("KEYS", "Description", ...) and o.bind_toggle("KEYS", "Description", ...)
# are the only two forms the Lua layer uses to declare a binding.
collect() {
  local file="$1"
  grep -ohE 'o\.bind(_toggle)?\(\s*"[^"]+",\s*"[^"]+"' "$file" 2>/dev/null |
    sed -E 's/o\.bind(_toggle)?\(\s*"([^"]+)",\s*"([^"]+)"/\2\t\3/'
}

section() {
  local title="$1"
  shift
  local rows
  rows="$(for file in "$@"; do collect "$file"; done | sort -u -t$'\t' -k1,1)"
  [[ -n $rows ]] || return 0

  echo
  echo "## $title"
  echo
  echo "| Keys | Action |"
  echo "| --- | --- |"
  printf '%s\n' "$rows" | while IFS=$'\t' read -r keys action; do
    printf '| `%s` | %s |\n' "$keys" "$action"
  done
}

{
  echo "# Keybindings"
  echo
  echo "Generated by \`blob-docs-keybinds\` from the \`o.bind\` calls in the Hyprland"
  echo "Lua files. Do not edit by hand."
  echo
  echo "Personal overrides in \`hypr/bindings.lua\` win over the defaults, and"
  echo "\`hl.unbind\` in that file removes a default outright."

  section "Personal" "$repo_dir/hypr/bindings.lua"
  section "Applications" "$repo_dir/default/hypr/bindings/applications.lua"
  section "Tiling" "$repo_dir/default/hypr/bindings/tiling.lua"
  section "Media" "$repo_dir/default/hypr/bindings/media.lua"
  section "Clipboard" "$repo_dir/default/hypr/bindings/clipboard.lua"
  section "Utilities" "$repo_dir/default/hypr/bindings/utilities.lua"

  echo
  echo "## Unbound defaults"
  echo
  grep -ohE 'hl\.unbind\("[^"]+"\)' "$repo_dir/hypr/bindings.lua" 2>/dev/null |
    sed -E 's/hl\.unbind\("([^"]+)"\)/- `\1`/' || echo "None."
} > "$output"

echo "Wrote $output"
