#!/usr/bin/env bash
# Video wallpaper support: discovery and still frames. Playback itself is
# mpvpaper, launched and supervised by services/VideoWallpaper.qml — this
# helper only answers questions a QML Process shouldn't shell-script inline.
#
#   scan <dir>              newest 60 videos under the folder, one path per line
#   frame <video> <out.png> a single still frame, for the lock screen
#
# The scan mirrors panama-wallpaper-scan's discipline exactly: two levels deep,
# newest first, a hard cap so a dumping-ground folder cannot flood the picker.

set -euo pipefail

command="${1:-}"

case "$command" in
scan)
    dir="${2:-}"
    [ -d "$dir" ] || exit 0
    find "$dir" -maxdepth 2 -type f \
        \( -iname '*.mp4' -o -iname '*.mkv' -o -iname '*.webm' \) \
        -printf '%T@ %p\n' 2>/dev/null | sort -rn | cut -d' ' -f2- | awk 'NR <= 60'
    ;;
frame)
    video="${2:-}"
    out="${3:-}"
    [ -f "$video" ] && [ -n "$out" ] || { echo "frame: bad arguments" >&2; exit 2; }
    # A second in: the first frame of a loop is often a fade from black.
    ffmpeg -hide_banner -loglevel error -ss 1 -i "$video" \
        -frames:v 1 -update 1 -y "$out.tmp.png" </dev/null
    mv "$out.tmp.png" "$out"
    ;;
*)
    echo "usage: panama-video-wallpaper scan <dir> | frame <video> <out.png>" >&2
    exit 2
    ;;
esac
