#!/usr/bin/env python3
"""Gestionnaire cPanel/MEGA. Privé, appelé uniquement par l'interface authentifiée.
Aucun secret n'est renvoyé au navigateur. Aucune suppression sans plan approuvé.
"""
import datetime as dt
import fcntl
import hashlib
import json
import os
import pathlib
import re
import secrets
import shutil
import stat
import subprocess
import sys
import tempfile
import time
import zipfile
from zoneinfo import ZoneInfo

HOME = pathlib.Path.home().resolve()
STORE = HOME / '.cpanel-mega-ui'
PLANS = STORE / 'plans'
JOBS = STORE / 'jobs'
WORK = STORE / 'work'
USER = os.environ.get('USER') or os.environ.get('LOGNAME') or HOME.name
PINNED = {'kiosk.prodisplay.ma','kio2.prodisplay.ma','prodisplay.ma'}
CACHE_REL = {'application/cache','application/logs','storage/cache','storage/logs',
             'storage/private/cache','storage/private/logs','system/cache'}
CONFIG_REL = ('application/config/database.php','application/config/production/database.php',
              'application/config/development/database.php','storage/private/config/database.php',
              'storage/private/config/app.php','storage/private/config/config.php',
              'config/database.php','.env','wp-config.php')
RE_DOMAIN = re.compile(r'(?=^.{4,253}$)^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])$')

def run(argv, timeout=45, check=True, input_data=None, text=False):
    p = subprocess.run(argv, input=input_data, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                       timeout=timeout, check=False, text=text)
    if check and p.returncode:
        raise RuntimeError(f"Échec outil {pathlib.Path(argv[0]).name} (code {p.returncode}); vérifier le journal privé")
    return p

def uapi(module, func, **params):
    cmd = shutil.which('uapi') or '/usr/local/cpanel/bin/uapi'
    if not os.path.exists(cmd): raise RuntimeError('UAPI cPanel introuvable')
    p = run([cmd, f'--user={USER}', '--output=json', module, func] + [f'{k}={v}' for k,v in params.items()],timeout=70)
    obj = json.loads(p.stdout)
    res = obj.get('result') or obj
    if res.get('status') not in (1,True): raise RuntimeError('Appel cPanel refusé : '+module+'/'+func)
    return res.get('data')

def flatten(value, group):
    if isinstance(value,list):
        return [x for v in value for x in flatten(v,group)]
    if isinstance(value,dict):
        if any(k in value for k in ('documentroot','document_root','docroot')):
            return [{'domain':str(value.get('domain') or value.get('servername') or ''),
                     'root':str(value.get('documentroot') or value.get('document_root') or value.get('docroot') or ''), 'type':group}]
        acc=[]
        for key,val in value.items():
            for row in flatten(val,group):
                if not row['domain']: row['domain']=str(key)
                acc.append(row)
        return acc
    return []

def discover():
    data=uapi('DomainInfo','domains_data',format='hash')
    names=uapi('DomainInfo','list_domains')
    if not isinstance(data,dict) or not isinstance(names,dict):
        raise RuntimeError('Formats cPanel inattendus')
    listed=set()
    for k in ('main_domain','addon_domains','sub_domains','parked_domains'):
        v=names.get(k,[])
        if isinstance(v,str): v=[v]
        if isinstance(v,list): listed.update(str(a).lower() for a in v)
    out={}
    for category in ('main_domain','addon_domains','sub_domains','parked_domains'):
        for row in flatten(data.get(category),category):
            name=row['domain'].strip().lower()
            if name not in listed or not RE_DOMAIN.fullmatch(name) or not row['root'].startswith('/'):
                raise RuntimeError('Incohérence des domaines cPanel')
            root=pathlib.Path(row['root']).resolve()
            if not root.is_relative_to(HOME):
                raise RuntimeError('Racine de domaine hors du compte')
            row['root']=str(root)
            if name in out and out[name]['root'] != str(root):
                raise RuntimeError('Racines contradictoires')
            out[name]=row
    if set(out)!=listed: raise RuntimeError('Liste de domaines incomplète : arrêt')
    return sorted(out.values(),key=lambda x:x['domain'])

def active_php(path):
    """Utilise token_get_all; les commentaires PHP sont ignorés par le lexer de PHP."""
    php=shutil.which('php')
    if not php: raise RuntimeError('PHP CLI requis pour analyser les commentaires de configuration')
    script=('foreach(token_get_all(file_get_contents($argv[1])) as $t) '
            '{ if(is_array($t)) { if($t[0]===T_COMMENT||$t[0]===T_DOC_COMMENT) '
            'echo str_repeat(" ",strlen($t[1])); else echo $t[1]; } else echo $t; }')
    return run([php,'-r',script,str(path)],timeout=10).stdout.decode('utf-8','replace')

def php_pairs(text):
    # Valeurs littérales uniquement ; aucune exécution de PHP, aucune interpolation dynamique.
    pat=r"['\"](?P<key>hostname|host|port|username|user|password|pass|database|dbname|db_name|DB_HOST|DB_USER|DB_PASSWORD|DB_NAME)['\"]\s*(?:=>|=)\s*(?P<q>['\"])(?P<val>(?:\\.|(?!\2).)*?)\2"
    matches=list(re.finditer(pat,text,re.I|re.S)); result={}
    for m in matches:
        val=m.group('val')
        if len(val)<1000 and '\n' not in val and '\r' not in val:
            result.setdefault(m.group('key').lower(),val.replace('\\\'','\'').replace('\\"','"'))
    wp=re.finditer(r"define\s*\(\s*['\"](DB_NAME|DB_USER|DB_PASSWORD|DB_HOST)['\"]\s*,\s*(['\"])(.*?)\2",text,re.I|re.S)
    for m in wp:result.setdefault(m.group(1).lower(),m.group(3))
    return result

def bracket_groups(text):
    # Découpe les groupes $db['default'] = [ ... ] / array(...) sans évaluer du code.
    rx=re.compile(r"\$db\s*\[\s*['\"]([a-zA-Z0-9_-]+)['\"]\s*\]\s*=\s*(?:array\s*\( |\[)",re.X)
    result=[]
    for m in rx.finditer(text):
        s=m.end(); op='(' if text[m.end()-1]=='(' else '['; cl=')' if op=='(' else ']'
        depth=1; quote=None; escape=False
        for i in range(s,len(text)):
            ch=text[i]
            if quote:
                if escape: escape=False
                elif ch=='\\': escape=True
                elif ch==quote: quote=None
            elif ch in ('"',"'"):quote=ch
            elif ch==op:depth+=1
            elif ch==cl:
                depth-=1
                if depth==0:
                    result.append((m.group(1),text[s:i]));break
    return result

def scan_db(root):
    found=[]; dynamic=False; consulted=[]
    for rel in CONFIG_REL:
        f=root/rel
        if not f.is_file() or f.is_symlink(): continue
        if f.stat().st_size>1024*1024:
            dynamic=True;continue
        consulted.append(rel)
        if rel=='.env':
            raw=f.read_text(errors='replace')
            text='\n'.join(x for x in raw.splitlines() if x.strip() and not x.lstrip().startswith('#'))
            props=dict((x.lower(),y.strip(' \"\'')) for x,y in re.findall(r'^\s*(DB_[A-Z_]+)\s*=\s*([^\r\n#]+)',text,re.M))
            blocks=[('env',props)]
        else:
            text=active_php(f)
            # Configurations dynamiques ou indirectes : jamais inférées par supposition.
            if re.search(r'\b(?:database|dbdriver|db_name|DB_NAME|DB_DATABASE)\b', text, re.I) and not re.search(r"['\"](?:database|db_name|DB_NAME)['\"]\s*(?:=>|=)\s*['\"]", text):
                dynamic=True
            # Cherche les groupes CI3 distincts, sinon les paires directes.
            groups=bracket_groups(text)
            blocks=[(g,php_pairs(segment)) for g,segment in groups] if groups else [('principal',php_pairs(text))]
            if re.search(r"\bgetenv\s*\(|\$_ENV|\$_SERVER|Private_config::get",text):dynamic=True
        for group,pairs in blocks:
            name=pairs.get('db_database') or pairs.get('database') or pairs.get('db_name')
            if not name:continue
            if not re.fullmatch(r'[a-zA-Z0-9_$.-]{1,128}',name):
                dynamic=True;continue
            host=pairs.get('db_host') or pairs.get('hostname') or pairs.get('host') or 'localhost'
            username=pairs.get('db_user') or pairs.get('db_username') or pairs.get('username') or pairs.get('user') or ''
            password=(pairs.get('db_password') if 'db_password' in pairs else
                      pairs.get('password',pairs.get('pass')))
            port=pairs.get('db_port') or pairs.get('port') or ''
            ident=hashlib.sha256(f'{rel}|{group}|{name}|{host}|{username}'.encode()).hexdigest()[:20]
            if not any(x['id']==ident for x in found):
                found.append({'id':ident,'name':name,'host':host,'username':username,'password':password,
                              'port':port,'source':rel,'group':group})
    if (root/'application').is_dir() and not consulted:
        dynamic=True  # Application non statique sans fichier SQL reconnaissable.
    return found,dynamic,consulted

def export_candidates(candidates):
    return [{k:v for k,v in item.items() if k!='password'} for item in candidates]

def owned_databases():
    try:
        data=uapi('Mysql','list_databases') or []
        return {x.get('database') or x.get('name') for x in data if isinstance(x,dict)}
    except Exception:return None

def mega_accounts():
    if not shutil.which('rclone'):return []
    p=run(['rclone','listremotes'],timeout=20)
    remotes=p.stdout.decode().splitlines(); out=[]
    for remote in remotes:
        remote=remote.rstrip(':')
        if not re.fullmatch(r'[a-zA-Z0-9_.-]+',remote):continue
        p=run(['rclone','config','show',remote],timeout=15,check=False)
        if p.returncode or not re.search(r'^type\s*=\s*mega\s*$',p.stdout.decode('utf-8','replace'),re.M):continue
        quota=run(['rclone','about','--json',remote+':'],timeout=45,check=False)
        data={}
        if quota.returncode==0:
            try:data=json.loads(quota.stdout)
            except ValueError:pass
        out.append({'name':remote,'total':data.get('total'),'used':data.get('used'),'free':data.get('free'),
                    'quota_ok':isinstance(data.get('free'),int) and data['free']>=0})
    return out

def size_bytes(root):
    # du -sk évite les symlinks et donne l'ordre de grandeur, pas la taille ZIP finale.
    p=run(['du','-sk',str(root)],timeout=90,check=False)
    if p.returncode:return None
    try:return int(p.stdout.split()[0])*1024
    except Exception:return None

def blockers_for(row, allrows, candidates):
    root=pathlib.Path(row['root']); blockers=[]
    if row['domain'] in PINNED:blockers.append('Site actif protégé : suppression désactivée')
    if row['type']!='sub_domains':blockers.append('Type de domaine non pris en charge pour suppression')
    if not root.is_dir() or root.is_symlink():blockers.append('Racine absente ou lien symbolique')
    if not root.is_relative_to(HOME/'public_html'):blockers.append('Racine hors de public_html')
    if len([a for a in allrows if a['root']==row['root']])>1:blockers.append('Racine web partagée avec un autre domaine')
    for other in allrows:
        if other['domain']!=row['domain'] and pathlib.Path(other['root']).is_relative_to(root):
            blockers.append('La racine contient un autre domaine : '+other['domain'])
    # Une configuration qui pointe vers un répertoire privé externe doit être
    # incluse dans la sauvegarde avant toute suppression. Ne pas prétendre à une
    # sauvegarde complète si ces références existent.
    for rel in CONFIG_REL + ('application/config/constants.php',):
        conf=root/rel
        if not conf.is_file() or conf.is_symlink() or conf.stat().st_size>512000:continue
        source=conf.read_text(errors='replace')
        for m in re.finditer(r'/home/[a-zA-Z0-9_-]+/(?:\.[a-zA-Z0-9_.-]+|storage-private)[a-zA-Z0-9_./-]*', source):
            external=pathlib.Path(m.group(0))
            if external.exists() and not external.is_relative_to(root):
                blockers.append('Dépendance privée hors du dossier : inclusion dans l’archive non démontrée')
                break
    # Détecte liens externes, CRON et intégration active hors du domaine
    if root.is_dir():
        for base,dirs,files in os.walk(root,followlinks=False):
            for fname in dirs+files:
                p=pathlib.Path(base)/fname
                if p.is_symlink():
                    try:p.resolve().relative_to(root)
                    except (ValueError,RuntimeError,OSError):blockers.append('Lien symbolique externe');break
            if 'Lien symbolique externe' in blockers:break
    cron=run(['crontab','-l'],check=False,timeout=8) if shutil.which('crontab') else None
    if cron and (str(root).encode() in cron.stdout or row['domain'].encode() in cron.stdout):
        blockers.append('Référence dans les tâches CRON')
    # Chemins des autres configs sur le compte : indications, pas garantie d'exhaustivité.
    for other in allrows:
        if other['domain']==row['domain']:continue
        r=pathlib.Path(other['root']);
        if not r.is_dir():continue
        for f in (r/'application/config/constants.php',r/'application/config/config.php',r/'storage/private/config/app.php'):
            if f.is_file() and not f.is_symlink() and f.stat().st_size < 512000:
                t=f.read_text(errors='replace')
                if str(root) in t: blockers.append('Référence au dossier dans une autre application');break
    return sorted(set(blockers))

def inspect(domain):
    allrows=discover()
    row=next((x for x in allrows if x['domain']==domain),None)
    if row is None:raise RuntimeError('Sous-domaine inexistant')
    root=pathlib.Path(row['root']);candidates,dynamic,consulted=scan_db(root) if root.is_dir() else ([],False,[])
    blockers=blockers_for(row,allrows,candidates)
    if dynamic and not candidates:blockers.append('Configuration SQL dynamique non résolue')
    warnings=[]
    if len({c['name'] for c in candidates})>1:
        warnings.append('Plusieurs bases non commentées : sélectionner explicitement la première réellement utilisée et vérifier son accès')
    owned=owned_databases()
    for item in candidates:
        item['owned']=None if owned is None else item['name'] in owned
    # La détection de DB partagée interdit toute suppression automatique.
    for item in candidates:
        other=[]
        for otherrow in allrows:
            if otherrow['domain']==domain or otherrow['root']==row['root']:continue
            r=pathlib.Path(otherrow['root'])
            if r.is_dir():
                oc,_,_=scan_db(r)
                if any(c['name']==item['name'] for c in oc):other.append(otherrow['domain'])
        item['shared_with']=other
    caches=[str(root/x) for x in sorted(CACHE_REL) if (root/x).is_dir() and not (root/x).is_symlink()]
    return {'domain':row['domain'],'root':row['root'],'type':row['type'],
            'size':size_bytes(root) if root.exists() else None,
            'db_candidates':export_candidates(candidates),'dynamic_config':dynamic,'configs':consulted,
            'blockers':sorted(set(blockers)),'warnings':warnings,'caches':caches,
            'recommended_archive':row['domain']+'-'+dt.datetime.now(ZoneInfo('Africa/Casablanca')).strftime('%Y-%m-%d')+'.zip',
            'pinned':row['domain'] in PINNED}

def annotate(root,domain,reasons):
    if not reasons:return
    target=root/'a-verifier-avant.md'
    if target.exists():return
    # Fichier documentaire placé à la demande dans le dossier concerné.
    # Aucune donnée de connexion ni valeur secrète.
    try:
        dbs, dynamic, configfiles=scan_db(root)
    except Exception:
        dbs=[];dynamic=True;configfiles=[]
    lines=['# À vérifier avant toute suppression','',
           f'**Sous-domaine :** `{domain}`',
           f'**Dossier cPanel :** `{root}`','',
           '## À quoi sert ce dossier ?',
           f'Ce répertoire est la racine web déclarée ou candidate du sous-domaine `{domain}`.',
           'Il peut contenir le code de l’application, ses fichiers privés, ses uploads, ses caches et journaux.',
           'Le supprimer peut rendre le domaine indisponible ou endommager une autre application qui en dépend.','',
           '## Configurations identifiées']
    lines.extend('- `'+x+'`' for x in configfiles)
    if not configfiles:lines.append('- Aucune configuration reconnue')
    lines+=['','## Bases SQL candidates (sans identifiants)']
    lines.extend('- `'+d['name']+'` (groupe '+d['group']+')' for d in dbs)
    if not dbs:lines.append('- Aucune base reconnue'+(' ; configuration dynamique possible' if dynamic else ''))
    lines+=['','## Ambiguïtés et dépendances à résoudre']
    lines+=['- '+reason for reason in reasons]
    lines+=['','## Vérifications obligatoires',
            '- Vérifier domaine et document root dans cPanel.',
            '- Confirmer la base effectivement utilisée et sa non-utilisation ailleurs.',
            '- Vérifier CRON, chemins privés externes et liens symboliques.',
            '- Obtenir une archive fichiers + SQL vérifiée par SHA-256 sur MEGA.',
            '- Ne supprimer qu’après validation explicite ; aucune action n’a été autorisée par cette note.',
            '', 'Aucun mot de passe, jeton ou secret ne figure dans ce document.']
    try:
        with os.fdopen(os.open(str(target),os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o644),'w') as f:
            f.write('\n'.join(lines)+'\n')
    except FileExistsError:pass


def newplan(request):
    domain=str(request.get('domain',''))
    selected=str(request.get('db_id',''))
    remote=str(request.get('remote',''))
    action=str(request.get('action','backup'))
    clean=bool(request.get('clean_cache',False))
    if action not in ('backup','backup_delete'):raise RuntimeError('Action inconnue')
    if not re.fullmatch(r'[a-zA-Z0-9_.-]+',remote):raise RuntimeError('MEGA invalide')
    overview=inspect(domain)
    rootpath=pathlib.Path(overview['root'])
    if not rootpath.is_dir() or rootpath.is_symlink() or not rootpath.is_relative_to(HOME):
        raise RuntimeError('Dossier source absent ou non sécurisé : sauvegarde impossible')
    options=mega_accounts(); m=next((r for r in options if r['name']==remote),None)
    if not m or not m['quota_ok']:raise RuntimeError('Compte MEGA sans quota vérifiable')
    real,_,_=scan_db(pathlib.Path(overview['root']))
    db=next((c for c in real if c['id']==selected),None) if selected else None
    if real and db is None:raise RuntimeError('Confirme explicitement la base active')
    if not real and overview['dynamic_config']:raise RuntimeError('Base dynamique non identifiée : intervention nécessaire')
    blockers=list(overview['blockers'])
    if db:
        if len({c['name'] for c in real})>1 and db['id'] != real[0]['id'] and action=='backup_delete':
            blockers.append('La base choisie n’est pas la première configuration active : revue manuelle nécessaire')
        matched=next(x for x in overview['db_candidates'] if x['id']==db['id'])
        if matched['owned'] is not True:blockers.append('Base non confirmée comme appartenant à cPanel')
        if matched['shared_with']:blockers.append('Base référencée par : '+', '.join(matched['shared_with']))
        if not db['username'] or db['password'] is None:blockers.append('Identifiants SQL manquants')
    reasons_to_note=[x for x in blockers if not x.startswith('Site actif protégé') and not x.startswith('Type de domaine')]
    if reasons_to_note or overview['warnings']:
        annotate(pathlib.Path(overview['root']),domain,reasons_to_note+overview['warnings'])
    if action=='backup_delete' and blockers:
        raise RuntimeError('Suppression bloquée : '+ '; '.join(blockers))
    if db and not sql_connection_ok(db):
        raise RuntimeError('La connexion à la base sélectionnée ne fonctionne pas : impossible de confirmer cette base')
    # Les bases ambiguës autorisent seulement la sauvegarde après choix explicite d'une base.
    if (overview['size'] or 0)>m['free']*.82:
        raise RuntimeError('Espace MEGA estimé insuffisant (marge de 18 %)')
    free_local=shutil.disk_usage(str(HOME)).free
    if overview['size'] is not None and overview['size']>free_local*.75:
        raise RuntimeError('Espace disque local estimé insuffisant pour le ZIP et le SQL')
    planid=secrets.token_hex(14)
    plan={'id':planid,'created':time.time(),'domain':domain,'root':overview['root'],
          'type':overview['type'],'db_id':selected,'db_name':db['name'] if db else None,
          'remote':remote,'action':action,'clean_cache':clean,'blockers':blockers,
          'archive':overview['recommended_archive'],'estimate':overview['size'],
          'remote_free':m['free'],'fingerprint':file_fingerprint(pathlib.Path(overview['root']))}
    save_json(PLANS/(planid+'.json'),plan)
    return {'plan_id':planid,'domain':domain,'root':overview['root'],'db_name':plan['db_name'],
            'archive':plan['archive'],'remote':remote,'free':m['free'],'size_estimate':overview['size'],
            'action':action,'clean_cache':clean,'warnings':blockers,'expires_in_seconds':600}

def file_fingerprint(root):
    h=hashlib.sha256()
    for rel in CONFIG_REL:
        f=root/rel
        if f.is_file():
            st=f.stat();h.update(f'{rel}|{st.st_size}|{st.st_mtime_ns}'.encode())
    return h.hexdigest()

def save_json(path,data):
    path.parent.mkdir(mode=0o700,parents=True,exist_ok=True)
    temp=path.with_suffix(path.suffix+'.new'+secrets.token_hex(4))
    with os.fdopen(os.open(temp,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600),'w') as f:
        json.dump(data,f,ensure_ascii=False,indent=2);f.flush();os.fsync(f.fileno())
    os.replace(temp,path)

def read_json(path):
    return json.loads(path.read_text())

def begin(req):
    pid=str(req.get('plan_id',''))
    if not re.fullmatch(r'[0-9a-f]{28}',pid):raise RuntimeError('Plan invalide')
    path=PLANS/(pid+'.json');plan=read_json(path)
    if time.time()-plan['created']>600:raise RuntimeError('Plan expiré : renouveler le résumé')
    if req.get('typed_domain')!=plan['domain'] or req.get('confirmed') is not True:
        raise RuntimeError('Confirmation du domaine obligatoire')
    if plan['action']=='backup_delete' and req.get('delete_confirm') is not True:
        raise RuntimeError('Confirmation explicite de suppression manquante')
    # Confirmation à usage unique : interdit deux déclenchements du même plan.
    claimed=PLANS/(pid+'.claimed')
    os.replace(path,claimed)
    jid=secrets.token_hex(14);folder=JOBS/jid;folder.mkdir(mode=0o700,parents=True,exist_ok=False)
    save_json(folder/'plan.json',plan)
    save_json(folder/'state.json',{'status':'queued','message':'En attente de lancement','progress':0})
    p=subprocess.Popen([sys.executable,__file__,'worker',jid],
                       stdin=subprocess.DEVNULL,stdout=open(folder/'worker.log','ab'),
                       stderr=subprocess.STDOUT,start_new_session=True,cwd=str(HOME))
    return {'job_id':jid,'pid':p.pid,'status':'queued'}

def state(jid):
    if not re.fullmatch(r'[0-9a-f]{28}',jid):raise RuntimeError('Job invalide')
    path=JOBS/jid/'state.json'
    if not path.is_file():raise RuntimeError('Job introuvable')
    return read_json(path)

def status(job,state_name,message,progress,**extra):
    data={'status':state_name,'message':message,'progress':progress,'updated':dt.datetime.now().isoformat()}
    data.update(extra);save_json(JOBS/job/'state.json',data)

def sha(path):
    h=hashlib.sha256()
    with path.open('rb') as f:
        for chunk in iter(lambda:f.read(4*1024*1024),b''):h.update(chunk)
    return h.hexdigest()

def sql_connection_ok(db):
    cli=shutil.which('mysql') or shutil.which('mariadb')
    if not cli or not db.get('username') or db.get('password') is None:
        return False
    esc=lambda x:'"'+str(x).replace('\\','\\\\').replace('"','\\"').replace('\n','\\n')+'"'
    with tempfile.TemporaryDirectory(prefix='sql-check-',dir=str(WORK)) as td:
        conf=pathlib.Path(td)/'my.cnf'
        with os.fdopen(os.open(conf,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600),'w') as f:
            f.write('[client]\nuser='+esc(db['username'])+'\npassword='+esc(db['password'])+'\nhost='+esc(db['host'])+'\n')
            if str(db.get('port','')).isdigit():f.write('port='+str(db['port'])+'\n')
        p=run([cli,'--defaults-extra-file='+str(conf),'--batch','--skip-column-names','-e','SELECT 1',db['name']],timeout=20,check=False)
        return p.returncode==0 and p.stdout.strip()==b'1'

def sql_dump(db,dest,tmp):
    binary=shutil.which('mariadb-dump') or shutil.which('mysqldump')
    if not binary:raise RuntimeError('mysqldump/mariadb-dump manquant')
    f=tmp/'sql-client.cnf'
    esc=lambda x:'"'+str(x).replace('\\','\\\\').replace('"','\\"').replace('\n','\\n')+'"'
    with os.fdopen(os.open(f,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600),'w') as h:
        h.write('[client]\nuser='+esc(db['username'])+'\npassword='+esc(db['password'])+'\n')
        h.write('host='+esc(db['host'])+'\n')
        if str(db['port']).isdigit():h.write('port='+str(db['port'])+'\n')
    try:
        with dest.open('wb') as outfile:
            p=subprocess.run([binary,'--defaults-extra-file='+str(f),'--single-transaction',
                   '--quick','--routines','--triggers','--events','--hex-blob','--databases',db['name']],
                   stdout=outfile,stderr=subprocess.PIPE,timeout=1800)
        if p.returncode or dest.stat().st_size<50:raise RuntimeError('Export SQL échoué : base non sauvegardée')
    finally:f.unlink(missing_ok=True)

def make_zip(root,target,sqlfile,metadata):
    with zipfile.ZipFile(target,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=6,allowZip64=True) as out:
        out.writestr('__backup/metadata.json',json.dumps(metadata,ensure_ascii=False,indent=2))
        if sqlfile:out.write(sqlfile,'__backup/database/'+metadata['database']+'.sql')
        for base,dirs,files in os.walk(root,topdown=True,followlinks=False):
            base=pathlib.Path(base); relative=str(base.relative_to(root)).replace(os.sep,'/')
            scrub=relative in CACHE_REL
            for dirname in list(dirs):
                if (base/dirname).is_symlink():
                    dirs.remove(dirname);files.append(dirname)
                elif scrub:dirs.remove(dirname)
            for name in files:
                f=base/name
                if scrub and name not in ('index.html','.htaccess'):continue
                arc=str(f.relative_to(root.parent)).replace(os.sep,'/')
                if f.is_symlink():
                    i=zipfile.ZipInfo(arc);i.create_system=3
                    i.external_attr=(stat.S_IFLNK|0o777)<<16
                    out.writestr(i,os.readlink(f))
                elif f.is_file():out.write(f,arc)
    with zipfile.ZipFile(target) as zipped:
        if zipped.testzip() is not None:raise RuntimeError('ZIP local non valide')

def remote_digest(target):
    proc=subprocess.Popen(['rclone','cat',target],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    h=hashlib.sha256()
    for chunk in iter(lambda:proc.stdout.read(4*1024*1024),b''):h.update(chunk)
    proc.stdout.close()
    err=proc.stderr.read();proc.stderr.close()
    code=proc.wait(timeout=3600)
    if code:raise RuntimeError('Relecture MEGA impossible')
    return h.hexdigest()

def clean_cache(root):
    cleaned=[]
    for relative in sorted(CACHE_REL):
        d=root/relative
        if not d.is_dir() or d.is_symlink():continue
        for item in d.iterdir():
            if item.name in ('index.html','.htaccess'):continue
            if item.is_symlink() or item.is_file():item.unlink()
            elif item.is_dir():shutil.rmtree(item)
        index=d/'index.html'
        if not index.exists():index.write_text('',encoding='utf-8')
        cleaned.append(relative)
    return cleaned

def worker(jid):
    folder=JOBS/jid; plan=read_json(folder/'plan.json')
    lockpath=STORE/'work.lock'
    with lockpath.open('a+') as lock:
        fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
        try:
            status(jid,'running','Revalidation du plan',5)
            domain=plan['domain'];rows=discover()
            row=next((r for r in rows if r['domain']==domain),None)
            if not row or row['root']!=plan['root']:raise RuntimeError('Racine cPanel modifiée : arrêt')
            root=pathlib.Path(row['root'])
            if file_fingerprint(root)!=plan['fingerprint']:raise RuntimeError('Configuration modifiée depuis validation')
            candidates,_,_=scan_db(root)
            db=next((x for x in candidates if x['id']==plan['db_id']),None) if plan['db_id'] else None
            if plan['db_id'] and not db:raise RuntimeError('Base sélectionnée introuvable')
            before=inspect(domain)
            if plan['action']=='backup_delete' and before['blockers']:
                annotate(root,domain,before['blockers']);raise RuntimeError('Dépendance détectée : suppression bloquée')
            if db and (not db['username'] or db['password'] is None):
                raise RuntimeError('Accès SQL non résolu')
            available=next((x for x in mega_accounts() if x['name']==plan['remote']),None)
            if not available or not available['quota_ok']:raise RuntimeError('MEGA indisponible ou quota inconnu')
            # Le dossier temporaire est hors public_html et ses permissions sont privées.
            with tempfile.TemporaryDirectory(dir=WORK,prefix='backup-') as tmp0:
                tmp=pathlib.Path(tmp0);os.chmod(tmp,0o700)
                dump=None
                if db:
                    status(jid,'running','Export de la base SQL',17)
                    dump=tmp/'database.sql';sql_dump(db,dump,tmp)
                status(jid,'running','Création du ZIP privé (logs/cache exclus)',35)
                local=tmp/plan['archive']
                meta={'domain':domain,'created':dt.datetime.now(dt.timezone.utc).isoformat(),
                      'database':db['name'] if db else None,'root_base':root.name,
                      'excluded_cache_logs':sorted(CACHE_REL), 'warnings':before['blockers']}
                make_zip(root,local,dump,meta)
                digest=sha(local)
                if local.stat().st_size > available['free']*.9:
                    raise RuntimeError('Espace libre MEGA insuffisant pour le ZIP final')
                dest=plan['remote']+':Sauvegardes/cPanel/'+plan['archive']
                status(jid,'running','Vérification des doublons sur MEGA',58)
                existing=run(['rclone','lsf','--files-only',plan['remote']+':Sauvegardes/cPanel'],check=False,timeout=60)
                existing_files=existing.stdout.decode(errors='replace').splitlines() if existing.returncode==0 else []
                if existing_files.count(plan['archive'])>1:
                    raise RuntimeError('MEGA contient plusieurs objets de même nom : désambiguïsation nécessaire')
                if existing_files.count(plan['archive'])==1:
                    if remote_digest(dest)!=digest:raise RuntimeError('Même nom mais archive MEGA différente : arrêt')
                else:
                    run(['rclone','mkdir',plan['remote']+':Sauvegardes/cPanel'],timeout=60)
                    status(jid,'running','Transfert du ZIP vers MEGA',67)
                    run(['rclone','copyto',str(local),dest,'--retries','3'],timeout=7200)
                status(jid,'running','Relecture et SHA-256 distant',83)
                if remote_digest(dest)!=digest:raise RuntimeError('SHA-256 distant différent : arrêt')
                # On laisse une preuve privée persistante même après suppression du domaine.
                evidence={'domain':domain,'zip':plan['archive'],'sha256':digest,'remote':plan['remote'],
                          'date':dt.datetime.now(dt.timezone.utc).isoformat(),'db':db['name'] if db else None}
                save_json(folder/'receipt.json',evidence)
                status(jid,'verified','Sauvegarde MEGA vérifiée',90,receipt=evidence)
                if plan['action']=='backup':
                    cleaned=clean_cache(root) if plan['clean_cache'] else []
                    status(jid,'done','Sauvegarde vérifiée ; domaine conservé',100,receipt=evidence,cleaned=cleaned)
                    return
                # Suppression exige un second contrôle juste avant la première action irréversible.
                latest=inspect(domain)
                if latest['blockers'] or not db and latest['db_candidates']:
                    annotate(root,domain,latest['blockers'] or ['Base non identifiée'])
                    raise RuntimeError('Nouvelle ambiguïté : suppression bloquée, sauvegarde disponible')
                if db:
                    own=owned_databases()
                    if own is None or db['name'] not in own:raise RuntimeError('Propriété DB non prouvée')
                    target=next((x for x in latest['db_candidates'] if x['id']==db['id']),None)
                    if not target or target['shared_with']:raise RuntimeError('Base partagée : suppression refusée')
                status(jid,'deleting','Suppression du sous-domaine cPanel',93,receipt=evidence)
                # Pour éviter de manipuler un domaine addon mal classé, uniquement vrais sous-domaines.
                known=[r['domain'] for r in rows if r['type'] in ('main_domain','addon_domains')]
                parents=sorted((n for n in known if domain.endswith('.'+n)),key=len,reverse=True)
                if not parents:raise RuntimeError('Domaine parent incertain')
                parent=parents[0];prefix=domain[:-(len(parent)+1)]
                # API cPanel : aucun rm ni DROP DATABASE avant confirmation du retrait du domaine.
                uapi('SubDomain','delsubdomain',domain=prefix,rootdomain=parent)
                if any(r['domain']==domain for r in discover()):
                    raise RuntimeError('Le domaine apparaît encore dans cPanel : arrêt après API')
                if db:
                    status(jid,'deleting','Suppression de la base via UAPI cPanel',96,receipt=evidence)
                    uapi('Mysql','delete_database',name=db['name'])
                    owns=owned_databases()
                    if owns is None or db['name'] in owns:
                        raise RuntimeError('Suppression DB non vérifiée : dossier préservé')
                # Ne jamais suivre de liens ou supprimer une racine différente.
                if root.exists():
                    if root.is_symlink() or not root.is_dir() or not root.is_relative_to(HOME/'public_html'):
                        raise RuntimeError('Chemin devenu dangereux : dossier préservé')
                    shutil.rmtree(root)
                status(jid,'done','Domaine, base et dossier supprimés après preuve MEGA',100,receipt=evidence)
        except Exception as ex:
            receipt=JOBS/jid/'receipt.json'
            extras={'receipt':read_json(receipt)} if receipt.exists() else {}
            status(jid,'error',str(ex),100,**extras)
            raise

def cli():
    command=sys.argv[1] if len(sys.argv)>1 else ''
    if command=='worker':
        worker(sys.argv[2]);return
    req=json.loads(sys.stdin.read() or '{}')
    try:
        if command=='domains':
            result={'domains':[{'domain':r['domain'],'root':r['root'],'type':r['type'],
                                'protected':r['domain'] in PINNED} for r in discover()]}
        elif command=='inspect':
            result={'detail':inspect(str(req.get('domain',''))),'remotes':mega_accounts()}
        elif command=='plan':result=newplan(req)
        elif command=='start':result=begin(req)
        elif command=='status':result=state(str(req.get('job_id','')))
        else:raise RuntimeError('Commande non autorisée')
        print(json.dumps({'ok':True,'data':result},ensure_ascii=False))
    except Exception as e:
        print(json.dumps({'ok':False,'error':str(e)},ensure_ascii=False))
        sys.exit(1)

if __name__=='__main__':cli()
