#!/bin/sh
set -eu

DB_DIR="$HOME/.local/share/cheat-sheets"
[ -d "$DB_DIR" ] || exit 1

# Stage 1: pick a sheet
sheet="$(
  ls "$DB_DIR"/*.tsv 2>/dev/null |
  xargs -I{} basename {} .tsv |
  rofi -dmenu -i -p 'Cheat sheet ›'
)" || exit 0
[ -n "${sheet:-}" ] || exit 0

db="$DB_DIR/${sheet}.tsv"
[ -f "$db" ] || exit 1

# Stage 2: search within the sheet
choice="$(rofi -dmenu -i -p "${sheet} ›" < "$db")" || exit 0
[ -n "${choice:-}" ] || exit 0

# Copy first column (keystroke/command) to clipboard
keys="$(printf '%s' "$choice" | cut -f1)"
if command -v xclip >/dev/null 2>&1; then
  printf '%s' "$keys" | xclip -selection clipboard
elif command -v xsel >/dev/null 2>&1; then
  printf '%s' "$keys" | xsel --clipboard --input
fi
