#!/bin/sh
#
# todotxt-dmenu - interact with todo.txt from dmenu
#
# see: https://git.sr.ht/~jboy/todotxt-dmenu/

height=$(todo.sh -p ls | tail -1 | awk '{ print $4 }')
[ "${height}" -gt 50 ] && height=50
prompt="➕✔️"

cmd=$(todo.sh -p ls |
  head -"${height}" |
  dmenu -i -l "${height}" -p "${prompt}")

while [ -n "${cmd}" ]; do
  if todo.sh -p ls | grep -q "^${cmd}\$" -; then
    # shellcheck disable=SC2312
    todo.sh -p "do" "$(echo "${cmd}" | awk '{ print $1 }')"
    height=$((height - 1))
  else
    todo.sh -p add "${cmd}"
    height=$((height + 1))
  fi

  cmd=$(todo.sh -p ls |
    head -"${height}" |
    dmenu -i -l "${height}" -p "${prompt}")
done

exit 0
