#!/bin/bash
# Author: Sean E. Russell <ser-legume@ser1.net>
# License: MIT
# (C) 2014 Sean E. Russell

if [[ $# -ne 0 ]]; then
  printf -- "A utility function to work with leg tickets using fzf\n"
  printf -- "\n"
  printf -- "Keybinds:\n"
  printf -- "- alt-r: Reload\n"
  printf -- "- alt-s: Show the item details\n"
  printf -- "- alt-e: Edit the text of the item (see the general top caveat)\n"
  printf -- "- alt-x: Marks task \"complete\" (read: deletes the comment line from the file; see caveat 1)\n"
  printf -- "- alt-d: Decreases the item priority (A -> B, B -> C, etc; see caveat 3)\n"
  printf -- "- alt-i: Increases the item priority (C -> B, B -> A, etc; see caveat 3)\n"
  printf -- "\n"
  printf -- "Dependencies:\n"
  printf -- "- The legume command is 'leg'\n"
  printf -- "- The 'fzf' command, of course\n"
  printf -- "- Standard POSIX tools: awk, head, read, sed, xargs, tr\n"
  printf -- "- GNU grep (with extended regular expression support via -E)\n"
  printf -- "\n"
  printf -- "Caveats:\n"
  printf -- "Quotes in items are OK, but '/' aren't well-handled as they interfere with the sed expressions.\n"
  printf -- "FIXME Complete function only works IFF the comment is alone on its line\n"
  printf -- "FIXME Inc/dec work IFF there isn't another priority syntax (\"\([A-Z]\)\") on the line, e.g. in code\n"
  exit 1
fi

leg | fzf \
	--bind 'alt-x:execute(leg $(echo "$1" | awk "{print \$1}") | head -n1 | IFS=: read -r FN LN ; sed -i "${FN}" -e "${LN}d")+reload(leg)' \
	--bind 'alt-r:reload(leg)' \
	--bind 'alt-s:execute(echo {} | awk "{print \$1}" | xargs -iX leg X && read)+reload(leg)' \
	--bind 'alt-e:execute(echo {} | awk "{print \$1}" | xargs -iX leg X | head -n1 | IFS=: read -r FN LN ; IFS=" " read -r k b E <<<{} ; O="$E" ; vared E ; sed -i "${FN}" -e "${LN}s/${O}/${E}/")+reload(leg)' \
	--bind 'alt-d:execute(echo {} | awk "{print \$1}" | xargs -iX leg X | head -n1 | IFS=: read -r FN LN ; D=$(sed "$FN" -ne "${LN}p" | grep -Eo "\([A-Z]\)" | tr "[A-Y]" "[B-Z]") ; sed -i "${FN}" -e "${LN}s/([A-Z])/$D/")+reload(leg)' \
	--bind 'alt-i:execute(echo {} | awk "{print \$1}" | xargs -iX leg X | head -n1 | IFS=: read -r FN LN ; D=$(sed "$FN" -ne "${LN}p" | grep -Eo "\([A-Z]\)" | tr "[B-Z]" "[A-Y]") ; sed -i "${FN}" -e "${LN}s/([A-Z])/$D/")+reload(leg)'
