#!/bin/sh
#
# jj - journal programs so small they only need one letter
#
# ---
# source: https://github.com/oridb/j

set -x

# default editor to vi
if [ -z "${EDITOR}" ]; then
  editor="vi"
else
  # otherwise use the system editor
  editor="${EDITOR}"
fi

# file references
# journal="${HOME}/journal"
journal="${HOME}/.local/share/journal/journal"
tmpfile="$(mktemp "${TMPDIR:-/tmp}"/j.XXXXXX)" || tmpfile=/tmp/j.$$

# file handling
trap 'rm -f "$tmpfile"' EXIT
touch "${tmpfile}"

# date variables
today=$(date -I)
now=$(date +"%Hh%M %z")
lastdate=$(grep '^===' "${journal}" | tail -n 1 | sed 's/ *=== *//g')

# handle command line arguments
args=$(getopt r: "$*")
if [ "$#" -ne 0 ]; then
  printf '%s\n' "usage: $(basename "$0") [-r rating] [msg...]"
  exit 2
fi
# we do want word splitting, so we won't put double quotes around it
# shellcheck disable=SC2086
set -- ${args}

# get variables for arguments
rating=""
# shellcheck disable=SC2249
while [ "$#" -ne 0 ]; do
  case "$1" in
    -r)
      rating="$2"
      shift
      ;;
    --)
      shift
      break
      ;;
  esac
  shift
done

# handle the entry
if [ -z "$*" ]; then
  # no arguments, go to the editor
  echo "$*"
  "${editor}" "${tmpfile}"
else
  # text was specified as arguments
  echo "$*" >>"${tmpfile}"
fi

# indent the body of the entry by two spaces
sed -i 's/^/  /g' "${tmpfile}"

# prepend the timestamp and metadata --
# if we had done this before, it would be visible in the editor
metadata=""
if [ -n "${rating}" ]; then
  metadata=" rating: ${rating}"
fi
# shellcheck disable=SC2312
printf '%s\n' "[${now}]${metadata}\n$(cat "${tmpfile}")" >"${tmpfile}"

# append the entry to the actual journal file
(
  # prepend the date and a newline if it's the first entry for the day
  if [ "${today}" != "${lastdate}" ]; then
    echo
    echo "=== ${today} ==="
  fi
  echo "  "

  # now indent another two spaces and output the entry and heading
  sed 's/^/  /g' <"${tmpfile}"
) >>"${journal}"
