#!/bin/bash
# VDQ maintenance automatique — pm2 one-shot cron 00:00 (process vdq-maintenance)
# Seuil : si downloads/ > VDQ_THRESHOLD (defaut 185) -> deplace les groupes
# complets les plus anciens des DOSSIERS BASE vers vDownloads jusqu'a VDQ_TARGET (defaut 100).
# Dossiers preserves (jamais deplaces) : share, clients, clips, cutting table,
# documentaries, telegram, home hacks, + tout dossier inconnu.
# Overrides manuels : VDQ_THRESHOLD, VDQ_TARGET, VDQ_DRYRUN=1
# Aucun grep pour le filtrage de dossiers (bug transport 2026-09-04) -> bash case uniquement.
set -uo pipefail
SRC=/volume2/VIDEO/videoDQ/downloads
DST=/volume2/VIDEO/vDownloads
LOG=/volume2/VIDEO/videoDQ/maintenance.log
PRESERVED="share clients clips cutting table documentaries telegram home hacks"
THRESHOLD="${VDQ_THRESHOLD:-185}"
TARGET="${VDQ_TARGET:-100}"
DRYRUN="${VDQ_DRYRUN:-0}"

ts() { date '+%Y-%m-%d %H:%M:%S'; }
log() { echo "[$(ts)] $*" >> "$LOG"; }
count_mp4() { find "$1" -type f -iname '*.mp4' ! -path '*@eaDir*' 2>/dev/null | wc -l; }
is_preserved() {
  local d="$1"
  local p
  for p in $PRESERVED; do [ "$d" = "$p" ] && return 0; done
  return 1
}

total=$(count_mp4 "$SRC")
log "check: total=$total threshold=$THRESHOLD target=$TARGET dryrun=$DRYRUN"
if [ "$total" -le "$THRESHOLD" ]; then
  log "no-op (total $total <= $THRESHOLD)"
  exit 0
fi

# Compter les preserved (bash pur)
preserved=0
while IFS= read -r f; do
  rel="${f#"$SRC"/}"
  d="${rel%%/*}"
  [ "$d" = "$rel" ] && continue
  if is_preserved "$d"; then preserved=$((preserved+1)); fi
done < <(find "$SRC" -type f -iname '*.mp4' ! -path '*@eaDir*')

if [ "$preserved" -ge "$TARGET" ]; then
  log "WARN: dossiers preserves ($preserved) >= cible ($TARGET) — aucun deplacement possible, intervention manuelle requise"
  exit 0
fi
to_move=$(( total - TARGET ))
if [ "$to_move" -le 0 ]; then log "no-op (rien a deplacer)"; exit 0; fi

# Candidats : dossiers base uniquement, les plus anciens d'abord (ctime)
CAND=/tmp/vdq_auto_candidates.txt
: > "$CAND"
while IFS= read -r line; do
  rel="${line#*	}"
  d="${rel%%/*}"
  [ "$d" = "$rel" ] && d=""
  if [ -n "$d" ] && is_preserved "$d"; then continue; fi
  echo "$rel" >> "$CAND"
done < <(find "$SRC" -type f -iname '*.mp4' ! -path '*@eaDir*' -printf '%C@	%P\n' | sort -n)

head -n "$to_move" "$CAND" > /tmp/vdq_auto_move.txt
if [ "$DRYRUN" = "1" ]; then
  log "DRYRUN: $to_move groupes seraient deplaces:"
  while IFS= read -r rel; do log "  DRYRUN $rel"; done < /tmp/vdq_auto_move.txt
  exit 0
fi

chmod u+w "$DST" 2>/dev/null
moved=0
while IFS= read -r rel; do
  [ -n "$rel" ] || continue
  subdir=$(dirname "$rel"); [ "$subdir" = "." ] && subdir=""
  if [ -n "$subdir" ] && is_preserved "$subdir"; then log "SKIP preserve: $rel"; continue; fi
  base=$(basename "$rel"); base=${base%.*}
  srcdir="$SRC"; dstdir="$DST"
  [ -n "$subdir" ] && srcdir="$SRC/$subdir" && dstdir="$DST/$subdir"
  mkdir -p "$dstdir"
  for f in "$srcdir/$base".*; do
    [ -e "$f" ] || continue
    case "$(basename "$f")" in *@eaDir*) continue;; esac
    if mv -v "$f" "$dstdir/" >> "$LOG" 2>&1; then moved=$((moved+1)); fi
  done
done < /tmp/vdq_auto_move.txt
log "done: moved_files=$moved total_avant=$total total_apres=$(count_mp4 "$SRC") vDownloads=$(count_mp4 "$DST")"
