#!/bin/bash
# Next calcurse item for xmobar: "<icon> 10:15<suffix>" for an appointment later today, the icon in the event colour
# for a whole-day event today, the icon alone when the next appointment is tomorrow; empty otherwise.
# With "list": show today's and tomorrow's items in a notification (for a click on the bar).
set -uo pipefail

usage="usage: calcurse-xmobar [--apt-color C] [--event-color C] [--icon TEXT] [--suffix TEXT] [list]"
apt_color='#ff79c6'
event_color='#8be9fd'
icon=$'\xf3\xb0\x83\xad'    # nf-md-calendar, as UTF-8 bytes so the locale doesn't matter
suffix=' | '
list=false
while (($#)); do
    case $1 in
    --apt-color) apt_color=$2; shift ;;
    --event-color) event_color=$2; shift ;;
    --icon) icon=$2; shift ;;
    --suffix) suffix=$2; shift ;;
    list) list=true ;;
    -h | --help) echo "$usage"; exit 0 ;;
    *) echo "$usage" >&2; exit 2 ;;
    esac
    shift
done
today=$(date +%F)

query() {
    calcurse -Q --filter-type cal --days 2 --output-datefmt %F "$@"
}

if $list; then
    tomorrow=$(date -d tomorrow +%F)
    body=$(query --format-apt '%S–%E  %m\n' --format-recur-apt '%S–%E  %m\n' \
        --format-event 'all day  %m\n' --format-recur-event 'all day  %m\n' |
        sed -e 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g' -e "s/^$today:$/Today:/; s/^$tomorrow:$/Tomorrow:/")
    notify-send -a calcurse -i x-office-calendar "Calendar" "${body:-Nothing today or tomorrow}"
    exit
fi

now=$(date +%s)
day="" next="" event=false
while read -r kind start; do
    case $kind in
    *:) day=${kind%:} ;;
    A) [[ -z $next ]] && ((start > now)) && next=$start ;;
    E) [[ $day == "$today" ]] && event=true ;;
    esac
done < <(query --format-apt 'A %s\n' --format-recur-apt 'A %s\n' --format-event 'E\n' --format-recur-event 'E\n')

if [[ -n $next && $(date -d "@$next" +%F) == "$today" ]]; then
    text="<fc=$apt_color>$icon $(date -d "@$next" +%H:%M)</fc>"
elif $event; then
    text="<fc=$event_color>$icon</fc>"
elif [[ -n $next ]]; then
    text="<fc=$apt_color>$icon</fc>"
else
    exit 0
fi
echo "$text$suffix"
