#!/usr/bin/env bash

# A script to parse the Hyprland configuration to store keybindings in a table

[[ -d "./docs" ]] || (echo "Folder ./docs not found" && exit 1)

KEYBINDINGS_FILE="./docs/KEYBINDINGS-HYPRLAND.md"

function getList() {
  content=$1
  name=$2
  list_start=$(echo "$content" | sed "/$name = \[/!d;=;Q")
  list=$(echo "$content" | tail +"$list_start")
  list_end=$(echo "$list" | sed '/\]/!d;=;Q')
  list=$(echo "$list" | head -n"$list_end")

  echo "$list"
}

[[ -f "./home/system/hyprland/bindings.nix" ]] || (echo "File ./home/system/hyprland/bindings.nix not found" && exit 1)

config=$(cat "./home/system/hyprland/bindings.nix")

# Bind
bind=$(getList "$config" "bind")
# Bindm (mouse)
bindm=$(getList "$config" "bindm")
# Bindl (lock)
bindl=$(getList "$config" "bindl")
# Bindle (lock, repetition)
bindle=$(getList "$config" "bindle")

# Join the lists:
keybindings=$(echo -e "$bind\n$bindm\n$bindl\n$bindle" | grep '"')

echo "[//]: # (This file is autogenerated)" >"$KEYBINDINGS_FILE"
echo "# Keybindings for Hyprland" >>"$KEYBINDINGS_FILE"
echo "" >>"$KEYBINDINGS_FILE"
echo "> [!NOTE]" >>"$KEYBINDINGS_FILE"
echo "> SUPER is the windows key by default" >>"$KEYBINDINGS_FILE"
echo "" >>"$KEYBINDINGS_FILE"

echo "| Description | Keybinding |" >>"$KEYBINDINGS_FILE"
echo "| -- | -- |" >>"$KEYBINDINGS_FILE"
echo "| Switch Workspace | SUPER + {Number} |" >>"$KEYBINDINGS_FILE"
echo "| Move app to Workspace | SHIFT + SUPER + {Number} |" >>"$KEYBINDINGS_FILE"
echo "$keybindings" | while read -r line; do
  comment=$(echo "$line" | cut -d\# -f2)
  line=$(echo "$line" | cut -d\# -f1)
  line=${line:1:${#line}-3}
  mod=$(echo "$line" | cut -d, -f1)
  key=$(echo "$line" | cut -d, -f2)
  # dispatcher=$(echo "$line" | cut -d, -f3)
  # params=$(echo "$line" | cut -d, -f4)

  [[ $mod == '$mod' ]] && mod="SUPER + "
  [[ $mod == '$shiftMod' ]] && mod="SHIFT + SUPER + "

  echo "| ${comment:1} | $mod$key |" >>"$KEYBINDINGS_FILE"
done
