#!/bin/sh
# This is inspired by dmenu's todo script made by suckless
#
# Manage TODO tasks in dmenu by writing them, remove by selecting
# an existing entry
#
# Configurable variables
# ---------------------------------------------------------------------

FILE="${XDG_DATA_HOME:-$HOME/.local/share}/todos"
PROMPT="Add/delete a task: "

# Logic
# ---------------------------------------------------------------------
mkdir -p "$(dirname $FILE)"
touch "$FILE"

height=$(wc -l "$FILE" | awk '{print $1}')

# Run dmenu and keep restarting it until it returns an empty output
cmd=$(dmenu -l "$height" -p "$PROMPT" "$@" < "$FILE")
while [ -n "$cmd" ]; do
    # If the output matched an existing TODO, remove it
    if grep -q "^$cmd\$" "$FILE"; then
        grep -v "^$cmd\$" "$FILE" > "$FILE.$$"
        mv "$FILE.$$" "$FILE"
        height=$(( height - 1 ))
    # If the output didn't match an existing TODO, it's a new one, add it
    else
        echo "$cmd" >> "$FILE"
        height=$(( height + 1 ))
    fi

    # Keep restarting until empty output
    cmd=$(dmenu -l "$height" -p "$PROMPT" "$@" < "$FILE")
done