"""OVH : copie serveur (statut « recu ») apres l'appel a la garde anti-spam, pour les formulaires hors FormProcessor.
Usage : python3 deploy_lc_ovh2.py [--apply]   (a lancer dans le home)"""
import sys, os, re, shutil, subprocess
APPLY = "--apply" in sys.argv
TAG = "lead-copy-20261106"
FIND = ("for ($__lcd = __DIR__, $__lci = 0; $__lci < 6; $__lci++, $__lcd = dirname($__lcd)) { if (@is_file($__lcd . '/_lead_copy.php')) "
        "{ require_once $__lcd . '/_lead_copy.php'; break; } } unset($__lcd, $__lci);")
ARM = " /* " + TAG + " */ " + FIND + " if (function_exists('lead_copy_arm')) { lead_copy_arm(basename(__FILE__)); }"
RX = re.compile(r"spam_guard_auto_die\([^;\n]*\);")
out = subprocess.run("grep -rl --include=*.php -e spam_guard_auto_die . 2>/dev/null", shell=True, capture_output=True, text=True, cwd=os.path.expanduser("~")).stdout.split()
st = {}
for rel in sorted(out):
    if re.search(r"bak|quarantine|_spam_guard\.php|FormProcessor\.php|/spam-guard/|sec2-tools|/back/@core|\$", rel):
        continue
    f = os.path.join(os.path.expanduser("~"), rel)
    s = open(f, encoding="utf-8", errors="surrogateescape").read()
    if TAG in s:
        st["deja"] = st.get("deja", 0) + 1; continue
    m = RX.search(s)
    if not m:
        st["sans_ancre"] = st.get("sans_ancre", 0) + 1; print("SANS_ANCRE", rel); continue
    s2 = s[:m.end()] + ARM + s[m.end():]
    st["ok"] = st.get("ok", 0) + 1
    if APPLY:
        shutil.copy2(f, f + ".bak-leadcopy-20261106")
        with open(f, "r+", encoding="utf-8", errors="surrogateescape") as fh:
            fh.seek(0); fh.write(s2); fh.truncate()
        if subprocess.run(["php", "-l", f], capture_output=True).returncode:
            shutil.copy2(f + ".bak-leadcopy-20261106", f); print("LINT_KO_RESTAURE", rel); st["lint_ko"] = st.get("lint_ko", 0) + 1
print(st, "apply=", APPLY)
