#!/bin/bash
# test : liste, sans rien changer.  go : remplace les fichiers piégés par les officiels de la même version.
cd ~ || exit 1
Q=~/hors-web-2026-10-06/fichiers-coeur-infectes
M='jschecks|order_llx|info_hash|token_hash|aHR0cHM6Ly8xMD|aHR0cHM6Ly80|\$[A-Za-z0-9_]{2,8}="[A-Za-z0-9_]{40,}";\$[A-Za-z0-9_]{2,8}=\$[A-Za-z0-9_]{2,8}\[[0-9]+\]\.'
[ -f ~/officiel-coeur.tar.gz ] && tar xzf ~/officiel-coeur.tar.gz -C ~
L=$(mktemp)
for s in */; do
  s=${s%/}; case "$s" in officiel-*) continue;; esac; [ -d "$s/classes" ] || continue
  if [ -f "$s/app/AppKernel.php" ]; then v=$(grep -o "VERSION = '[0-9.]*'" "$s/app/AppKernel.php" | grep -o "[0-9.]*[0-9]")
  else v=$(grep -o "_PS_VERSION_', *'[0-9.]*'" "$s/config/settings.inc.php" 2>/dev/null | grep -o "[0-9][0-9.]*[0-9]"); fi
  O=~/officiel-$v
  echo "== $s (PrestaShop $v)"
  for d in classes controllers src override config vendor/smarty tools/smarty; do [ -d "$s/$d" ] && grep -rlE --include='*.php' "$M" "$s/$d" 2>/dev/null; done | sort -u > "$L"
  for i in "$s"/img/*.png "$s"/img/*.jpg "$s"/img/*.gif; do [ -f "$i" ] || continue; h=$(head -c 4 "$i" | od -An -c | tr -d " "); case "$h" in *PNG*|*GIF8*|*377330377*) ;; *) echo "$i";; esac; done >> "$L"
  [ -s "$L" ] || { echo "rien trouvé"; continue; }
  while IFS= read -r f; do
    r=${f#$s/}
    if [ "$1" != "go" ]; then [ -f "$O/$r" ] || case "$r" in img/*) ;; *) echo -n "(pas d'officiel) ";; esac; echo "piégé : $f"; continue; fi
    mkdir -p "$Q/$(dirname "$f")"; [ -f "$Q/$f" ] || cp -p "$f" "$Q/$f"
    case "$r" in img/*) mv "$f" "$Q/$f.retire" && echo "retiré : $f"; continue;; esac
    if [ -f "$O/$r" ]; then
      cp "$O/$r" "$f.officiel" && php -l "$f.officiel" >/dev/null 2>&1 && cat "$f.officiel" > "$f" && rm -f "$f.officiel" && echo "remplacé par l'officiel $v : $f" || { rm -f "$f.officiel"; echo "ÉCHEC : $f"; }
    else
      echo "À TRAITER À LA MAIN (pas d'officiel $v) : $f"
    fi
  done < "$L"
  if [ "$1" = "go" ] && [ -d "$s/var/cache/prod" ]; then mv "$s/var/cache/prod" "$s/var/cache/prod-apres-nettoyage-$(date +%H%M)"; fi
done
rm -f "$L"
echo "== fin"
