#!/bin/sh
#
# today -- what did you do today?

set -e
err() {
  echo "$*" 1>&2
}

die() {
  err "$*"
  exit 1
}

DIR=${TODAY_DIR:-$HOME/.today}
LOG=$DIR/log

gitdo() {
  git -C "$DIR" "$@"
}

commit() {
  if ! gitdo diff --quiet; then
    gitdo add "$LOG"
    gitdo commit --quiet -m "$@"
  else
    echo "No changes, exiting"
  fi
}

init() {
  mkdir -p "$DIR"
  [ -d "$DIR/.git" ] && die "$DIR exists as a git repo already"
  gitdo init -b main
  cat <<EOM >"$LOG"
today -- what did you do today?
-------------------------------
EOM
  gitdo add "$LOG"
  gitdo commit -m "Initial commit"
}

reqinit() {
  if [ ! -d "$DIR" ]; then
    die "$DIR doesn't exist; init with -i first or set \$TODAY_DIR"
  fi
}

edlog() {
  ed -s -p'ed> ' "$@" "$LOG"
  commit "Auto commit"
}

edit() {
  now=$(printf "[%s]" "$(date "+%F")")
  if grep -q "^\[$(date "+%F")\]\$" "$LOG"; then
    echo "Entry for today already exists, editing"
  else
    echo "Starting a new entry for today $now"
    printf "\n$now\n" >>"$LOG"
  fi
  edlog
}

list() {
  re='^\[[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\]$'
  case "x$1" in
    x) cat "$LOG" ;;
    x[0-9]*)
      i="$1"
      N="$(grep "$re" "$LOG" | wc -l)"
      if [ $i -gt $N ]; then
        cat "$LOG"
        return
      fi
      rm -f /tmp/today.ed
      while [ $i -gt 0 ]; do
        i=$((i - 1))
        printf "?%s?;" "$re" >>/tmp/today.ed
      done
      printf "\$p\nq\n" >>/tmp/today.ed
      ed -s "$LOG" </tmp/today.ed
      ;;
    *) die "$1 isn't a number" ;;
  esac
}

case "x$1" in
  x) reqinit && edit ;;
  x-e) reqinit && ${EDITOR:-vi} "$LOG" ;;
  x-i) init ;;
  x-l) reqinit && list "$2" ;;
  x-h) die "usage: today [-ehi] [-l [NUM]]" ;;
  *)
    [ -n "$1" ] && err "error: unknown option $1"
    die "usage: today [-ehi] [-l [NUM]]"
    ;;
esac
