#!/bin/bash
# Rollout einvoicing 20260920 sur une instance OVH. argv1=NAME argv2=htdocs.
# Backup + snapshot + rsync staging (code 20260920 + vendor) + migration + 2 toggles + vérifs + lint. PAS d'init.
set -e
NAME="$1"; H="$2"
ST="$HOME/pichinov/_refresh_einv2/staging/einvoicing"
SC="$HOME/pichinov/_stage_einv120_scripts"
LIVE="$H/custom/einvoicing"
TS=$(date +%Y%m%d-%H%M%S)
BK="$HOME/pichinov/backups/einv-rollout-$NAME-$TS"

echo "######## $NAME ($H) ########"
[ -f "$ST/VERSION" ] || { echo "STAGING manquant, abort"; exit 2; }
if [ ! -f "$LIVE/VERSION" ]; then echo ">>> einvoicing ABSENT sur $NAME → SKIP"; exit 0; fi
echo "VERSION avant: $(cat "$LIVE/VERSION")"
mkdir -p "$BK"

echo "=== backup arbre + snapshot consts avant ==="
cp -a "$LIVE" "$BK/einvoicing"
echo "backup: $(find "$BK/einvoicing" -type f | wc -l) fichiers -> $BK"
php "$SC/einv_snapshot.php" "$H" > "$BK/consts_before.txt" 2>/dev/null
echo "consts avant: $(wc -l < "$BK/consts_before.txt")"

echo "=== fichiers live-only hors vendor (seront supprimés par --delete) ==="
( cd "$LIVE" && LC_ALL=C find . -type f | grep -v '/vendor/' | LC_ALL=C sort ) > "$BK/live_files.txt"
( cd "$ST" && LC_ALL=C find . -type f | grep -v '/vendor/' | LC_ALL=C sort ) > "$BK/tree_files.txt"
LC_ALL=C comm -23 "$BK/live_files.txt" "$BK/tree_files.txt" | sed 's/^/  DEL /'
echo "  (attendu: XmlPatcher, PriceHelper, ajax/document.php, éventuels tests — tous non-runtime)"

echo "=== rsync staging -> live (--delete, vendor inclus) ==="
rsync -a --delete --exclude='.git' --chmod=D755,F644 "$ST/" "$LIVE/"
echo "VERSION après: $(cat "$LIVE/VERSION")"

echo "=== migration + toggles ==="
php "$SC/einv_migrate.php" "$H"

echo "=== consts après + diff (attendu: +2 toggles, reste inchangé) ==="
php "$SC/einv_snapshot.php" "$H" > "$BK/consts_after.txt" 2>/dev/null
diff "$BK/consts_before.txt" "$BK/consts_after.txt" || true

echo "=== vérifs ==="
echo "  EmbeddedXmlReader: $([ -f "$LIVE/class/utils/EmbeddedXmlReader.class.php" ] && echo OK || echo MANQUE) | XmlPatcher absent: $([ ! -f "$LIVE/class/utils/XmlPatcher.class.php" ] && echo OK || echo 'PRÉSENT!') | ajax/document.php absent: $([ ! -f "$LIVE/ajax/document.php" ] && echo OK || echo 'PRÉSENT!')"
php "$SC/einv_verify.php" "$H" 2>&1 | grep -viE "Deprecated|PHP Warning|Warning: Undefined|Notice"

echo "=== lint échantillon runtime ==="
for f in class/providers/SuperPDPProvider.class.php class/providers/AbstractPDPProvider.class.php core/modules/modEInvoicing.class.php class/utils/EmbeddedXmlReader.class.php public/proxy_oauthcallback.php sync_pending_list.php; do
  if [ -f "$LIVE/$f" ]; then php -l "$LIVE/$f" >/dev/null 2>&1 && echo "  OK $f" || echo "  !!! KO $f"; fi
done
echo "######## $NAME TERMINÉ (backup $BK) ########"
