#!/usr/bin/env bash
#
# autorender.sh — self-updating nightly render driver for the render rig.
#
# Invoked by Windows Task Scheduler (run only when user is logged on):
#   wsl.exe -d Ubuntu -u glitchhunter -- bash -lc "/home/glitchhunter/Projects/gnommo/autorender.sh"
#
# Flow:
#   1. DEPLOY CODE — git fetch + reset --hard origin/<branch>, then re-exec the
#      freshly pulled script once. This is how code changes ship from the Mac:
#      push to origin, and the next run picks them up. SAFE — reset --hard only
#      rewrites TRACKED files; gitignored project data (video*/) and secrets
#      (.env) are left untouched. This script NEVER runs `git clean`.
#   2. RENDER — (pending) `gnommo auto`: per-project down -> gated render -> handoff.
#
# Config via environment (set once in ~/.profile / ~/.bash_profile on the rig,
# so a login shell — bash -lc — picks them up):
#   GNOMMO_DIR   repo clone on the rig          (default: this script's own dir)
#   BRANCH       branch to track                (default: main)
#   NTFY_URL     failure ping endpoint, e.g.    https://ntfy.sh/your-secret-topic
#
set -uo pipefail

# Default GNOMMO_DIR to the repo this script lives in, so it works regardless of
# username or checkout path (rig: /home/glitchhunter/Projects/gnommo).
GNOMMO_DIR="${GNOMMO_DIR:-$(cd "$(dirname "$(readlink -f "$0")")" && pwd)}"
BRANCH="${AUTORENDER_BRANCH:-main}"
LOG="${AUTORENDER_LOG:-$GNOMMO_DIR/autorender.log}"
LOCK="${AUTORENDER_LOCK:-/tmp/gnommo-autorender.lock}"

log()    { printf '%s | %s\n' "$(date '+%F %T')" "$*" | tee -a "$LOG"; }
notify() { [ -n "${NTFY_URL:-}" ] && curl -fsS -m 10 -d "$*" "$NTFY_URL" >/dev/null 2>&1 || true; }

# ── Step 1: deploy latest code from origin, then re-exec the fresh script once ──
# The re-exec is essential: reset --hard rewrites this very file mid-run, so we
# must restart from the updated copy rather than keep executing the old bytes.
if [ -z "${AUTORENDER_UPDATED:-}" ]; then
    if ! cd "$GNOMMO_DIR" 2>/dev/null; then
        log "FATAL: GNOMMO_DIR not found: $GNOMMO_DIR"
        notify "autorender: GNOMMO_DIR missing ($GNOMMO_DIR)"
        exit 1
    fi
    if git fetch --quiet origin 2>>"$LOG"; then
        before="$(git rev-parse --short HEAD 2>/dev/null || echo '?')"
        git reset --hard "origin/$BRANCH" >>"$LOG" 2>&1
        after="$(git rev-parse --short HEAD 2>/dev/null || echo '?')"
        ./venv/bin/pip install -e . -q >>"$LOG" 2>&1 || true  # catch new deps/entry points
        [ "$before" != "$after" ] && log "code deployed: $before -> $after"
    else
        log "git fetch failed — running existing code"
        notify "autorender: git fetch failed on the rig"
    fi
    export AUTORENDER_UPDATED=1
    exec "$0" "$@"
fi

# ── everything below runs on the freshly-deployed code ─────────────────────────

# Single-run lock — renders take hours; a second scheduled firing must bail.
exec 9>"$LOCK"
if ! flock -n 9; then
    log "another autorender run is active — exiting"
    exit 0
fi

log "autorender start (HEAD $(git -C "$GNOMMO_DIR" rev-parse --short HEAD 2>/dev/null), user $(whoami))"

# ── Step 2: render loop — per-project down → gated render → handoff ────────────
# `gnommo auto` scans video* under the cwd, so cd into the repo first. It returns
# non-zero if any project failed; we ping on that.
cd "$GNOMMO_DIR"
if ./venv/bin/python -m gnommo auto 2>&1 | tee -a "$LOG"; then
    log "autorender done (all projects ok)"
else
    log "autorender done WITH FAILURES (see log above)"
    notify "autorender: one or more projects failed on the rig — check autorender.log"
fi
