#!/usr/bin/env bash
# ~/bin/FOURb — FOUR + simple scp upload (no sudo)
set -euo pipefail

# ---------- CONFIG: remote upload ----------
HOST="227.lupton.us"                     # basement server hostname
REMOTE_USER="pi"                          # remote user
REMOTE_DIR="/var/www/html/stratum-S"      # remote web dir (group-writable by www-data)
REMOTE="${REMOTE_USER}@${HOST}"

# ---------- ENV / paths ----------
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
OUTDIR="$HOME/html/stratum-S"
mkdir -p "$OUTDIR"
cd "$OUTDIR"

# Align to next minute, log it
sleep $((60 - 10#$(date +%S))); date | tee -a date.log

# ---------- feeds ----------
feeds=(
  "https://www.youtube.com/watch?v=z1PJqpgZccg|capetown|Cape Town live"
  "https://www.youtube.com/watch?v=ydYDqZQpim8|nambia|Nambia live"
  "https://www.youtube.com/watch?v=4VR91TGYDz4|iceland|Iceland live"
  "https://www.youtube.com/watch?v=_OeFhA2XqqA|canal|Cape Cod Canal live"
  "https://www.youtube.com/watch?v=sQxL8t0gtu8|chicago|Chicago live"
  "https://www.youtube.com/watch?v=6g4Fh8K-MhY|hawaii|Hawaii live"
)


# ---------- snapshot each feed ----------
for entry in "${feeds[@]}"; do
  IFS="|" read -r URL BASENAME LABEL <<<"$entry"
  ts="$(date +'%y%m%d.%H%M')"
  tmpdir="$(mktemp -d)"
  tmp_jpg="${tmpdir}/frame.jpg"

  # Resolve direct media URL (best)
  stream_url="$(yt-dlp --no-playlist -f 'b' --get-url "$URL" | head -n 1)"

  # Grab a quick chunk and snap first frame
  ffmpeg -y -loglevel error -t 5 -i "$stream_url" -frames:v 1 -f image2 "$tmp_jpg"

  # Annotate near bottom-left (moved down 45px from your old +88 -> +43)
  magick "$tmp_jpg" -resize 640x480 \
    -gravity SouthWest -fill yellow -undercolor black -pointsize 24 \
    -annotate +10+43 "${LABEL}  ${ts}" \
    "$OUTDIR/${BASENAME}_${ts}.jpg"

  cp "$OUTDIR/${BASENAME}_${ts}.jpg" "$OUTDIR/${BASENAME}_latest.jpg"
  rm -rf "$tmpdir"
done

# ---------- build tile ----------
# (your existing tile.sh handles making tile.jpg and tile.mmdd.HHMM.jpg)
"$HOME/bin/tile.sh"

# pick up the outputs we expect
STAMP="$(date '+%m%d.%H%M')"
LIVE="$OUTDIR/tile.jpg"
STAMPED="$OUTDIR/tile.${STAMP}.jpg"

echo "Wrote composite: $LIVE and $STAMPED"

# ---------- simple upload (no sudo) ----------
# Requires: key-based auth for $REMOTE_USER and $REMOTE_USER able to write to $REMOTE_DIR
# See: sudo usermod -aG www-data pi; chgrp -R www-data /var/www/html/stratum-S; chmod -R g+ws ...
echo "➡️  Uploading to ${REMOTE}:${REMOTE_DIR}/"
scp -q -o BatchMode=yes -o StrictHostKeyChecking=accept-new \
  "$LIVE" "$STAMPED" "${REMOTE}:${REMOTE_DIR}/" || {
  echo "⚠️  scp failed (no sudo used). Check SSH key or directory perms." >&2
  exit 1
}

# quick HEAD check (HTTP or HTTPS as configured)
if curl -sI --max-time 8 "http://${HOST}/stratum-S/tile.jpg" | head -1 | grep -q "200"; then
  echo "✅ Remote tile reachable over HTTP."
else
  echo "ℹ️  Skipped HTTP check or not reachable; verify manually if needed."
fi
