import re, os, sys, glob

# Signature de la backdoor : bloc if(isset($_REQUEST)...) jusqu'aux accolades après die();
pattern = re.compile(
    r'[ \t]*if\s*\(\s*isset\(\$_REQUEST\)\s*&&\s*isset\(\$_REQUEST\[[^\]]*\]\)\)\s*\{.*?die\s*\(\s*\)\s*;(?:\s*\})+',
    re.DOTALL
)

root = sys.argv[1] if len(sys.argv) > 1 else '.'
dry  = '--apply' not in sys.argv
cleaned = 0
for path in glob.glob(os.path.join(root, '**', '*.php'), recursive=True):
    try:
        with open(path, 'r', encoding='utf-8', errors='surrogateescape') as f:
            data = f.read()
    except Exception as e:
        print('SKIP', path, e); continue
    new = pattern.sub('', data)
    if new != data:
        cleaned += 1
        if dry:
            print('[dry-run] infecté :', path)
        else:
            with open(path + '.bak', 'w', encoding='utf-8', errors='surrogateescape') as f:
                f.write(data)
            with open(path, 'w', encoding='utf-8', errors='surrogateescape') as f:
                f.write(new)
            print('nettoyé   :', path)
print(('[dry-run] ' if dry else '') + 'total :', cleaned, 'fichier(s)')
