#!/bin/bash
# Phase B : swap atomique arbre 1.2.0 + migration idempotente + vérifs. PAS d'init().
set -e
DROOT="$HOME/pichinov/dolibarr/htdocs"
LIVE="$DROOT/custom/einvoicing"
ST="$HOME/pichinov/_stage_einv120"
SCRIPTS="$HOME/pichinov/_stage_einv120_scripts"
TS=$(cat "$HOME/pichinov/_stage_einv120_TS")
BK="$HOME/pichinov/backups/einv-maj120-$TS"

echo "TS=$TS"
echo "BK=$BK"
[ -f "$ST/einvoicing/VERSION" ] || { echo "staging manquant"; exit 2; }
[ -f "$BK/consts_before.txt" ] || { echo "snapshot AVANT manquant"; exit 2; }

echo "=== SWAP : rsync -a --delete (staging -> live) ==="
rsync -a --delete --exclude='.git' --chmod=D755,F644 "$ST/einvoicing/" "$LIVE/"
echo "live VERSION après swap = $(cat "$LIVE/VERSION")"
echo "résidus .orig restants (doit être vide) :"
ls "$LIVE"/class/providers/*.orig "$LIVE"/core/modules/*.orig 2>/dev/null || echo "  (aucun) ✅"

echo "=== MIGRATION update_v1.2.0.sql (idempotent, pas d'init) ==="
php "$SCRIPTS/migrate120.php"

echo "=== SNAPSHOT consts APRÈS + diff avec AVANT ==="
php "$SCRIPTS/consts_snapshot.php" > "$BK/consts_after.txt" 2>/dev/null
echo "consts APRÈS = $(wc -l < "$BK/consts_after.txt")"
if diff "$BK/consts_before.txt" "$BK/consts_after.txt" >/dev/null; then
	echo "CONSTS INCHANGÉES ✅ (avant == après, proxy préservé)"
else
	echo "!!! CONSTS MODIFIÉES (à examiner) :"
	diff "$BK/consts_before.txt" "$BK/consts_after.txt"
fi

echo "=== VÉRIFS finales ==="
php "$SCRIPTS/verify120.php"

echo "=== LINT live (échantillon runtime clé) ==="
for f in class/providers/SuperPDPProvider.class.php core/modules/modEInvoicing.class.php public/proxy_oauthcallback.php lib/einvoicing.lib.php sync_pending_list.php class/einvoicingsyncpending.class.php; do
	php -l "$LIVE/$f" >/dev/null 2>&1 && echo "  OK $f" || echo "  !!! LINT KO $f"
done
echo "=== PHASE B TERMINÉE (TS=$TS) ==="
