#!/bin/sh
# A to-do list on BlueRune's desktop, from a plain text file: one thing to do a line, written
# "- [ ] Call the plumber" (or just "Call the plumber"), and "- [x] Water the plants" once
# it's done. Lines that are empty or start with # are left alone.
#
# The card shows what is left first, and a press on a line ticks it in the file (or unticks
# it). Its buttons open the file to edit it, and clear away what is done. BlueRune keeps the
# card (it is made with `bluerunectl ext set`), so it stays across restarts; run this script
# again whenever the file changes, for example from a systemd path unit.
#
# BLUERUNE_TODO_FILE names the file; without it, ~/todo.txt. See docs/extensions.md.
set -eu

file=${BLUERUNE_TODO_FILE:-$HOME/todo.txt}
# The most lines the card lists, as BlueRune allows.
most=8

# $1 as a JSON string: quotes and backslashes escaped, tabs made spaces and other control
# characters dropped, and cut to 60 characters (BlueRune takes 64).
json() {
    printf '%s' "$1" | tr '\t' ' ' | tr -d '\000-\037' | sed -E 's/^(.{59}).+$/\1…/; s/\\/\\\\/g; s/"/\\"/g; s/^/"/; s/$/"/'
}

# $1 quoted for sh -c.
quote() {
    printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
}

# Every thing to do as "line<TAB>done<TAB>words": done is 1 or 0.
items() {
    [ -f "$file" ] || return 0
    awk '
        /^[[:space:]]*$/ || /^[[:space:]]*#/ { next }
        {
            line = $0; done = 0
            if (match(line, /^[[:space:]]*[-*][[:space:]]+\[[xX]\][[:space:]]*/)) { done = 1; line = substr(line, RLENGTH + 1) }
            else if (match(line, /^[[:space:]]*[-*][[:space:]]+\[[[:space:]]\][[:space:]]*/)) { line = substr(line, RLENGTH + 1) }
            else if (match(line, /^[[:space:]]*[-*][[:space:]]+/)) { line = substr(line, RLENGTH + 1) }
            if (line != "") printf "%d\t%d\t%s\n", NR, done, line
        }' "$file"
}

# Ticks line $1 of the file, or unticks it.
toggle() {
    case $1 in '' | *[!0-9]*) return 0 ;; esac
    awk -v at="$1" '
        NR == at {
            if (match($0, /^[[:space:]]*[-*][[:space:]]+\[[xX]\]/)) { $0 = substr($0, 1, RLENGTH - 3) "[ ]" substr($0, RLENGTH + 1) }
            else if (match($0, /^[[:space:]]*[-*][[:space:]]+\[[[:space:]]\]/)) { $0 = substr($0, 1, RLENGTH - 3) "[x]" substr($0, RLENGTH + 1) }
            else if (match($0, /^[[:space:]]*[-*][[:space:]]+/)) { $0 = substr($0, 1, RLENGTH) "[x] " substr($0, RLENGTH + 1) }
            else { $0 = "- [x] " $0 }
        }
        { print }' "$file" >"$file.new"
    mv "$file.new" "$file"
}

# Takes the lines that are done out of the file.
clear_done() {
    awk '!/^[[:space:]]*[-*][[:space:]]+\[[xX]\]/' "$file" >"$file.new"
    mv "$file.new" "$file"
}

publish() {
    all=$(items)
    total=$(printf '%s' "$all" | grep -c . || true)
    left=$(printf '%s\n' "$all" | awk -F '\t' '$2 == 0' | grep -c . || true)
    # What is left first, then what is done, each in the file's order.
    rows=$(printf '%s\n' "$all" | grep . | sort -s -t "$(printf '\t')" -k2,2n | head -n "$most" | while IFS="$(printf '\t')" read -r line done words; do
        checked=false
        [ "$done" = 1 ] && checked=true
        printf '{"text": %s, "checked": %s, "action": "%s"},' "$(json "$words")" "$checked" "$line"
    done)
    if [ "$total" -eq 0 ]; then
        detail="Nothing to do"
        rows='{"text": "Add things to do to the file, one a line"},'
    elif [ "$left" -eq 0 ]; then
        detail="All done"
    else
        detail="$left left of $total"
    fi
    if [ "$total" -gt "$most" ]; then
        detail="$detail, $((total - most)) not shown"
    fi
    content=$(printf '{"list": [%s], "buttons": [{"label": "Edit", "icon": "edit", "action": "edit"}, {"label": "Clear done", "action": "clear"}]}' "${rows%,}")
    script=$(cd "$(dirname "$0")" && pwd)/$(basename "$0")
    bluerunectl ext set todo --slot desktop --name "To do" --icon checklist --hue green \
        --detail "$detail" --content "$content" \
        --on-click "BLUERUNE_TODO_FILE=$(quote "$file") $(quote "$script")"
}

# Opens the file to edit it, made first when there is none yet.
edit() {
    [ -e "$file" ] || : >"$file"
    exec xdg-open "$file"
}

case ${BLUERUNE_ACTION:-} in
item) toggle "${BLUERUNE_VALUE:-}" ;;
button)
    case ${BLUERUNE_VALUE:-} in
    edit | '') edit ;;
    clear) [ -f "$file" ] && clear_done ;;
    esac
    ;;
activate) edit ;;
esac
publish
