"""Copie serveur des demandes sur OVH mutualise (a lancer dans le home du compte).
Usage : python3 deploy_lc_ovh.py [--apply] fichier_FormProcessor...
"""
import sys, os, re, shutil, subprocess
APPLY = "--apply" in sys.argv
HOME = os.path.expanduser("~")
TAG = "lead-copy-20261106"
SUF = ".bak-leadcopy-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('FormProcessor'); lead_copy_track(); }"
SG = "unset($__sgd, $__sgi);"
MAIL = "$sent = @mail($to, $subject, $message, $headers);"
STAT = MAIL + " /* " + TAG + " */ if (function_exists('lead_copy_status')) { lead_copy_status($sent ? 'envoye' : 'echec_mail', !empty($GLOBALS['FP_RC_FLAG']) ? 'reCAPTCHA ' . $GLOBALS['FP_RC_FLAG'] : ''); }"
PROC = re.compile(r"public function process\(\$form\)\s*\{")
stats = {}
for f in [a for a in sys.argv[1:] if a != "--apply"]:
    s = open(f, encoding="utf-8", errors="surrogateescape").read()
    if TAG in s:
        stats["deja"] = stats.get("deja", 0) + 1; continue
    ST = " /* " + TAG + " */ if (function_exists('lead_copy_status')) { lead_copy_status(%s ? 'envoye' : 'echec_mail', !empty($GLOBALS['FP_RC_FLAG']) ? 'reCAPTCHA ' . $GLOBALS['FP_RC_FLAG'] : ''); }"
    m3 = re.findall(r"\$sent = \$mailer->send\([^\n;]*\);", s)
    if s.count(MAIL) == 1:
        mail_o, mail_n = MAIL, STAT
    elif s.count("$mail->send();") == 1:
        mail_o, mail_n = "$mail->send();", "$mail->send();" + ST % "true"
    elif len(m3) == 1:
        mail_o, mail_n = m3[0], m3[0] + ST % "$sent"
    else:
        # envoi non identifiable (PHPMailer embarque) : copie gardee avec le statut « recu »
        mail_o, mail_n = None, None
    arm = ARM if mail_o else ARM.replace(" lead_copy_track();", "")
    if s.count(SG) == 1:
        s2 = s.replace(SG, SG + arm, 1)
    elif len(PROC.findall(s)) == 1:
        s2 = PROC.sub(lambda m: m.group(0) + arm, s, count=1)
    else:
        print("ANCRE_ARM_KO", f); continue
    if mail_o:
        s2 = s2.replace(mail_o, mail_n, 1)
    k = "ok" if mail_o else "ok_statut_recu"
    stats[k] = stats.get(k, 0) + 1
    if APPLY:
        shutil.copy2(f, f + SUF)
        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 + SUF, f); print("LINT_KO_RESTAURE", f)
if APPLY:
    shutil.copy2(HOME + "/_lead_copy.php.new", HOME + "/_lead_copy.php"); os.chmod(HOME + "/_lead_copy.php", 0o644)
    os.makedirs(HOME + "/lead-copies", exist_ok=True); os.chmod(HOME + "/lead-copies", 0o750)
print(stats, "apply=", APPLY)
