#!/usr/bin/env bash
# run_all_timelapses.sh
#
# Run timelapse creation for a fixed set of webcams,
# collect public URLs, update HTML index, and send one combined ntfy notification.
#
# Requirements: make_timelapse.sh in same folder or PATH

set -euo pipefail

# --- Settings ---
BASE_DIR="/media/photos/misc/webcams"
INDEX_FILE="$BASE_DIR/timelapses.html"
WEBCAMS=(
  "frontyard"
  "basement_table"
  "mailbox"
  "basement_extension"
  "backyard_low"
  "backyard_north"
  "backyard_house"
  "basement_cape"
  "basement_tv"
  "backyard"
  "bulkhead"
  "barn"
  "penobscot"
  "birds"
  "clouds"
  "porch"
  "firewood"
  "garden"
  "diningroom"
  "office"
  "office_birds"
  "ducks"
)
TIMELAPSE_SCRIPT="/usr/local/bin/make_timelapse"

NTFY_URL="https://ntfy.unbl.ink/timelapse"
WEB_PREFIX="https://files.lab.unbl.ink/webcams"
# ----------------

# Yesterday's date
if date -d "yesterday" +%Y >/dev/null 2>&1; then
  # GNU date (Linux)
  YESTERDAY=$(date -d "yesterday" +"%Y/%m/%d")
else
  # BSD date (macOS)
  YESTERDAY=$(date -v-1d +"%Y/%m/%d")
fi

LINKS=()

for cam in "${WEBCAMS[@]}"; do
  TARGET_DIR="$BASE_DIR/$cam/$YESTERDAY"

  if [[ -d "$TARGET_DIR" ]]; then
    echo "📷 Processing $cam ($TARGET_DIR)"
    OUTPUT=$("$TIMELAPSE_SCRIPT" "$TARGET_DIR")
    echo "$OUTPUT"

    LINK="$WEB_PREFIX/$cam/$YESTERDAY/timelapse.mp4"
    if [[ -f "$TARGET_DIR/timelapse.mp4" ]]; then
      LINKS+=("[$cam] $LINK")
    fi
  else
    echo "⚠️ Skipping $cam (no folder for $YESTERDAY)"
  fi
done

# --- Update index.html ---
INDEX_HTML="$BASE_DIR/timelapses.html"

# Ensure file exists with basic structure
if [[ ! -f "$INDEX_HTML" ]]; then
  cat > "$INDEX_HTML" <<EOF
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Webcam Timelapses</title>
</head>
<body>
  <h1>Webcam Timelapses</h1>
  <div id="days">
  </div>
</body>
</html>
EOF
fi

# Build new day's section
NEW_SECTION="<h2>$YESTERDAY</h2><ul>"
for link in "${LINKS[@]}"; do
  cam=$(echo "$link" | cut -d']' -f1 | tr -d '[]')
  url=$(echo "$link" | awk '{print $2}')
  NEW_SECTION+="<li><a href=\"$url\">$cam</a></li>"
done
NEW_SECTION+="</ul>"

# Insert at the top of <div id="days">
tmpfile=$(mktemp)
awk -v section="$NEW_SECTION" '
  /<div id="days">/ { print; print section; next }
  { print }
' "$INDEX_HTML" > "$tmpfile"
mv "$tmpfile" "$INDEX_HTML"

echo "📝 Updated index with $YESTERDAY timelapses (newest on top)"

# --- Send combined notification ---
if [[ -n "$NTFY_URL" ]] && [[ ${#LINKS[@]} -gt 0 ]]; then
  MSG="Timelapses for $YESTERDAY:\n$(printf '%s\n' "${LINKS[@]}")"
  curl -s -H "Title: Timelapses complete" \
       -H "Priority: high" \
       -d "$MSG" \
       "$NTFY_URL" >/dev/null || true
  echo "📢 Combined notification sent to ntfy."
fi

