#!/bin/bash
# One-shot, and the "once" is load-bearing. launchd's StartCalendarInterval
# repeats daily and launchd has no run-once — so without a guard this story
# goes out again every night at 20:00 forever.
#
# TWO defences, deliberately, because they fail differently:
#   1. the .published marker, checked first. This is the PRIMARY guard and it
#      needs no privileges, so it holds even if (2) fails.
#   2. removing the job. Best-effort: this runs as marcusminim4 out of a
#      LaunchDaemon, and `sudo -n` from a non-interactive launchd context is not
#      guaranteed. If it fails, (1) still stops a second post.
set -u
MARKER="$HOME/porthole/.published"
LOG="$HOME/.config/porthole/publish.log"

remove_job() {
  sudo -n launchctl bootout system/com.marcus.porthole.story 2>/dev/null \
    || echo "$(date) could not unload the job — the marker is what stops a repeat" >> "$LOG"
  sudo -n rm -f /Library/LaunchDaemons/com.marcus.porthole.story.plist 2>/dev/null
}

cd "$HOME/porthole" || exit 1

if [ -f "$MARKER" ]; then
  echo "$(date) already published; refusing to repeat" >> "$LOG"
  remove_job
  exit 0
fi

if /usr/bin/python3 publish-story.py hanoi-story.mp4 --apply; then
  # Marker BEFORE the unload: if the unload hangs, the marker is already down
  # and tomorrow's run stops at the check above.
  date > "$MARKER"
  remove_job
else
  echo "$(date) publish FAILED — leaving the job loaded so it can be inspected" >> "$LOG"
fi
