#!/bin/bash
# VDQ maintenance automatique - pm2 one-shot cron 00:00 (process vdq-maintenance)
# Phase 1 (telegram) : garder les TELEGRAM_KEEP (21) plus recentes dans
#   downloads/telegram, deplacer le reste vers vDownloads/telegram - chaque nuit,
#   independant du seuil (decision Luc 2026-09-13).
# Phase 2 (seuil global) : si downloads/ > VDQ_THRESHOLD (defaut 185), deplacer les
#   groupes complets les plus anciens des DOSSIERS BASE vers vDownloads jusqu a
#   VDQ_TARGET (defaut 140).
# Liste blanche (2026-09-13, decision Luc) : seuls les dossiers base connus sont
#   candidats en phase 2 ; tout autre dossier (preserves + inconnus, ex: Gander)
#   est preserve integralement.
# Overrides : VDQ_THRESHOLD, VDQ_TARGET, TELEGRAM_KEEP, VDQ_DRYRUN=1
# Aucun grep pour le filtrage (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
BASE_DIRS="twitter facebook instagram linkedin youtube tiktok rumble other"
TELEGRAM_KEEP="${TELEGRAM_KEEP:-21}"
THRESHOLD="${VDQ_THRESHOLD:-185}"
TARGET="${VDQ_TARGET:-140}"
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_base() {
  local d="$1"; local p
  for p in $BASE_DIRS; do [ "$d" = "$p" ] && return 0; done
  return 1
}

total=$(count_mp4 "$SRC")
log "check: total=$total threshold=$THRESHOLD target=$TARGET tg_keep=$TELEGRAM_KEEP dryrun=$DRYRUN"

# ---------- Phase 1 : cap telegram ----------
TG="$SRC/telegram"
tg_count=$(count_mp4 "$TG")
if [ "$tg_count" -gt "$TELEGRAM_KEEP" ]; then
  tg_move=$((tg_count - TELEGRAM_KEEP))
  # Les plus anciennes d abord ; chemin relatif a SRC (telegram/<fichier>)
  find "$TG" -type f -iname '*.mp4' ! -path '*@eaDir*' -printf '%C@ telegram/%P\n' | sort -n | head -n "$tg_move" | cut -d' ' -f2- > /tmp/vdq_tg_move.txt
  if [ "$DRYRUN" = "1" ]; then
    log "DRYRUN telegram: $tg_move groupes seraient deplaces:"
    while IFS= read -r rel; do log "  DRYRUN-TG $rel"; done < /tmp/vdq_tg_move.txt
  else
    chmod u+w "$DST" 2>/dev/null
    mkdir -p "$DST/telegram"
    chmod a+rwx "$DST/telegram" 2>/dev/null
    moved=0
    while IFS= read -r rel; do
      [ -n "$rel" ] || continue
      case "$rel" in telegram/*) ;; *) continue;; esac
      base=$(basename "$rel"); base=${base%.*}
      for f in "$TG/$base".*; do
        [ -e "$f" ] || continue
        case "$(basename "$f")" in *@eaDir*) continue;; esac
        if mv -v "$f" "$DST/telegram/" >> "$LOG" 2>&1; then moved=$((moved+1)); fi
      done
    done < /tmp/vdq_tg_move.txt
    log "telegram: moved_files=$moved tg_avant=$tg_count tg_apres=$(count_mp4 "$TG")"
  fi
else
  log "telegram: ok ($tg_count <= $TELEGRAM_KEEP)"
fi

# ---------- Phase 2 : seuil global, dossiers base ----------
total=$(count_mp4 "$SRC")
base_count=0
while IFS= read -r f; do
  rel="${f#"$SRC"/}"
  d="${rel%%/*}"
  [ "$d" = "$rel" ] && continue
  is_base "$d" && base_count=$((base_count+1))
done < <(find "$SRC" -type f -iname '*.mp4' ! -path '*@eaDir*')

to_move=$(( total - TARGET ))
if [ "$base_count" -le 0 ]; then
  log "WARN: aucune video dans les dossiers base (total $total = preserves/inconnus)"
elif [ "$to_move" -le 0 ]; then
  log "no-op phase2 (total $total <= target $TARGET)"
else
  CAND=/tmp/vdq_auto_candidates.txt
  : > "$CAND"
  while IFS= read -r line; do
    rel="${line#* }"
    d="${rel%%/*}"
    [ "$d" = "$rel" ] && d=""
    if [ -n "$d" ] && ! is_base "$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
  else
    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_base "$subdir"; then log "SKIP non-base: $rel"; continue; fi
      base=$(basename "$rel"); base=${base%.*}
      srcdir="$SRC"; dstdir="$DST"
      [ -n "$subdir" ] && srcdir="$SRC/$subdir" && dstdir="$DST/$subdir"
      mkdir -p "$dstdir"
      chmod a+rwx "$dstdir" 2>/dev/null
      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 "base: moved_files=$moved total_avant=$total total_apres=$(count_mp4 "$SRC") vDownloads=$(count_mp4 "$DST")"
  fi
fi

# ---------- P5b : sweep permissions downloads ----------
perm_count=$(find "$SRC" -type f ! -perm /004 ! -name ".*" ! -path "*@eaDir*" | wc -l)
if [ "$perm_count" -gt 0 ]; then
    find "$SRC" -type f ! -perm /004 ! -name ".*" ! -path "*@eaDir*" -exec chmod a+rw {} +
    find "$SRC" -type d ! -perm /005 ! -name "@eaDir*" -exec chmod a+rwx {} +
    log "perms: $perm_count fichier(s) non-lisible(s) corriges (chmod a+rw)"
fi