#!/bin/bash
# Prints a cached thumbnail for the video in $1 (used by the lf preview), creating it if needed.
# Thumbnails are named by a hash of path, size and mtime, so a changed file gets a new one.
# Hits touch the file; systemd-tmpfiles (~/.config/user-tmpfiles.d/vidthumb.conf) removes unused ones.

[[ -f $1 ]] || exit 1

cache="${XDG_CACHE_HOME:-$HOME/.cache}/vidthumb"
video=$(realpath -- "$1") || exit 1
stamp=$(stat -c '%s.%Y' -- "$video") || exit 1
key=$(printf '%s\0%s' "$video" "$stamp" | sha256sum)
thumb="$cache/${key%% *}.jpg"

if [[ -s $thumb ]]; then
    touch -- "$thumb"
    printf '%s\n' "$thumb"
    exit 0
fi

mkdir -p -- "$cache" || exit 1
# Write to a temp file first, so an interrupted or concurrent run never leaves a broken thumbnail.
tmp=$(mktemp --suffix=.jpg "$cache/.tmp.XXXXXX") || exit 1
if ffmpegthumbnailer -i "$video" -o "$tmp" -s 0 2> /dev/null && [[ -s $tmp ]]; then
    mv -f -- "$tmp" "$thumb"
    printf '%s\n' "$thumb"
else
    rm -f -- "$tmp"
    exit 1
fi
