#!/bin/bash
# Log return from lunch.
set -euo pipefail

F="$HOME/long-day-factory.json"
TS="$(python3 -c 'import datetime;print(datetime.datetime.now().astimezone().isoformat(timespec="seconds"))')"
ALSO_LUNCH="${1:-}"

if [ ! -f "$F" ]; then
  printf '{\n  "startTime": null,\n  "lunchTime": null,\n  "backToWork": null\n}\n' > "$F"
fi

tmp="$(mktemp)"
if [ "$ALSO_LUNCH" = "--also-lunch" ]; then
  jq --arg ts "$TS" '.backToWork = $ts | (if .lunchTime == null then .lunchTime = $ts else . end)' "$F" > "$tmp" && mv "$tmp" "$F"
  echo "Back to work at $TS (also set lunchTime to $TS)"
else
  jq --arg ts "$TS" '.backToWork = $ts' "$F" > "$tmp" && mv "$tmp" "$F"
  echo "Back to work at $TS"
fi

if [ "$(jq -r '.lunchTime' "$F")" = "null" ]; then
  echo "WARNING: lunchTime is not set — ask the user if they want to set it now (--also-lunch)."
fi
if [ "$(jq -r '.startTime' "$F")" = "null" ]; then
  echo "WARNING: startTime is not set — did you skip long-day-start this morning?"
fi
