#!/usr/bin/sh
set -eu

CONFIG=${YA_CONFIG:-/etc/yabo/config}
# shellcheck source=/dev/null
. "$CONFIG"

# A "video" is any sibling that is not a generated sidecar (nfo/info.json/thumb).
has_video() {
  base=$1
  for f in "$base".*; do
    [ -e "$f" ] || continue
    case $f in
      *.nfo|*.info.json|*.jpg|*.jpeg|*.png|*.webp) ;;
      *) return 0 ;;
    esac
  done
  return 1
}

# When the video is gone, remove its leftover sidecars so Kodi shows no ghost
# and thumbnails/metadata don't accumulate. Channel.rec and the .rss-* dotfiles
# are never touched: they don't match "$base".*, so ledger and download
# tombstone survive.
sweep_orphans() {
  find "$YA_ROOT" -type f -name '*.nfo' ! -name 'tvshow.nfo' | while read -r nfo; do
    base=${nfo%.nfo}
    has_video "$base" && continue
    for f in "$base".nfo "$base".info.json "$base".jpg "$base".jpeg "$base".png "$base".webp; do
      rm -f "$f"
    done
  done
}

sweep_orphans
