#!/usr/bin/env python3
"""ZFS -> bounded native chunk stream; never stage the send payload on disk."""
import argparse
from contextlib import contextmanager
import datetime
import fcntl
import hashlib
import io
import json
import os
from pathlib import Path
import re
import shlex
import signal
import stat
import subprocess
import threading
from collections import deque
import sys
import time
import uuid

# SSH sessions on Python 3.6 may use ASCII even though status text is UTF-8.
_original_stdio = []
for _name in ('stdout', 'stderr'):
    _stream = getattr(sys, _name)
    if hasattr(_stream, 'buffer') and (_stream.encoding or '').lower() in ('ascii', 'ansi_x3.4-1968'):
        _original_stdio.append(_stream)
        setattr(sys, _name, io.TextIOWrapper(_stream.buffer, encoding='utf-8', errors='backslashreplace', line_buffering=True))

ENGINE = os.environ.get('SCHIPSAVE_BIN', '/usr/bin/schipsave')
ZFS = os.environ.get('SCHIPSAVE_ZFS_BIN', 'zfs')
FORMAT = 'schipsave-zfs-stream-v1'


def require(condition, message):
    if not condition:
        raise RuntimeError(message)


def identifier(value, dataset=False):
    pattern = r'[A-Za-z0-9][A-Za-z0-9_.:/-]*' if dataset else r'[A-Za-z0-9][A-Za-z0-9_.-]{0,127}'
    require(isinstance(value, str) and re.fullmatch(pattern, value), 'identificador inválido')
    if dataset:
        require(not any(p in ('', '.', '..') for p in value.split('/')), 'dataset inválido')
    return value


def command(args, check=True, input_data=None):
    process = subprocess.Popen(list(map(str, args)), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                               stdin=subprocess.PIPE if input_data is not None else None)
    try:
        out, err = process.communicate(input_data)
    except BaseException:
        process.terminate()
        try:
            process.wait(timeout=5)
        except subprocess.TimeoutExpired:
            process.kill()
            process.wait()
        raise
    if check and process.returncode:
        raise RuntimeError('comando falhou: {}: {}'.format(args[0], err.decode(errors='replace')[-2000:]))
    return process.returncode, out


def zget(prop, name):
    return command([ZFS, 'get', '-Hp', '-o', 'value', prop, name])[1].decode().strip()


def remote(args, command_args):
    if args.host == '--local':
        return [ENGINE] + (['--lock-wait','86400'] if getattr(args,'restore_wait',False) else []) + command_args
    require(re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9@._:\[\]-]*', args.host), 'host SSH inválido')
    ssh = ['ssh', '-T', '-oBatchMode=yes', '-oStrictHostKeyChecking=yes', '-oConnectTimeout=30',
           '-oServerAliveInterval=30', '-oServerAliveCountMax=3']
    if os.environ.get('SCHIPSAVE_SSH_CONFIG'):
        ssh += ['-F', os.environ['SCHIPSAVE_SSH_CONFIG']]
    return ssh + [args.host, ' '.join(shlex.quote(s) for s in ['schipsave'] + command_args)]


def capability(args):
    require(command([ENGINE, '--stream-protocol'])[1].strip() == b'1', 'agente sem suporte a fluxo')
    status, output = command([ENGINE, '--zfs-stream-protocol'], check=False)
    require(status == 0 and output.strip() == b'1', 'atualize o agente para deduplicação por registros ZFS')
    require(command(remote(args, ['stream-query']), input_data=query(args))[1].strip() == b'1', 'repositório sem suporte a fluxo')
    request = query(args)
    status, output = command(remote(args, ['stream-query']), check=False, input_data=request[:8] + b'\x02' + request[9:])
    require(status == 0 and output.strip() == b'1',
            'atualize o repositório para restauração por registros ZFS')
    if getattr(args, 'synthetic', False):
        synthetic_capability(args)


def synthetic_capability(args):
    status, output = command([ENGINE, '--zfs-synthetic-protocol'], check=False)
    require(status == 0 and output.strip() == b'1', 'atualize o agente para full sintético ZFS')
    request = query(args)
    status, output = command(remote(args, ['stream-query']), check=False, input_data=request[:8] + b'\x03' + request[9:])
    require(status == 0 and output.strip() == b'1', 'atualize o servidor para full sintético ZFS')


def query(args, snapshot=None, path='metadata.json'):
    machine = getattr(args, 'machine', None)
    if not machine:
        match = re.fullmatch(r'(.+)--[0-9]{8}T[0-9]{6}Z-[0-9a-f]{16}', args.snapshot)
        require(match is not None, 'nome de backup nativo inválido')
        machine = match.group(1)
    fields = [(args.repo, 4096), (machine, 65), (snapshot or '', 129), (path, 16)]
    output = b'SCHIPS01' + bytes([int(snapshot is not None)])
    for text, size in fields:
        encoded = text.encode()
        require(b'\0' not in encoded and len(encoded) < size, 'campo de consulta inválido')
        output += encoded + b'\0' * (size - len(encoded))
    return output


def atomic(path, value):
    temporary = path.with_name('.' + path.name + '-' + uuid.uuid4().hex)
    fd = os.open(str(temporary), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    try:
        with os.fdopen(fd, 'w') as output:
            json.dump(value, output, sort_keys=True)
            output.flush()
            os.fsync(output.fileno())
        os.replace(str(temporary), str(path))
        sync_directory(path.parent)
    finally:
        if temporary.exists():
            temporary.unlink()


def sync_directory(path):
    directory = os.open(str(path), os.O_RDONLY | os.O_DIRECTORY)
    try:
        os.fsync(directory)
    finally:
        os.close(directory)


def private_directory(path):
    require(path.is_absolute(), 'diretório de estado deve ser absoluto')
    path.mkdir(mode=0o700, parents=True, exist_ok=True)
    info = path.lstat()
    require(stat.S_ISDIR(info.st_mode) and info.st_uid == os.geteuid() and
            stat.S_IMODE(info.st_mode) == 0o700, 'estado deve ser diretório privado 0700 do executor')
    for ancestor in path.parents:
        info = ancestor.lstat()
        require(stat.S_ISDIR(info.st_mode) and info.st_uid in (0, os.geteuid()) and
                not (info.st_mode & 0o022 and not info.st_mode & stat.S_ISVTX),
                'ancestral do estado permite escrita de terceiros')


def validate_metadata(value):
    require(isinstance(value, dict), 'metadados inválidos')
    require(value.get('format') == FORMAT, 'formato de fluxo desconhecido')
    require(value.get('stream_encoding') in (None, 'zfs-records-v1'), 'codificação de fluxo desconhecida')
    identifier(value['dataset'], True)
    identifier(value['snapshot_name'])
    require(value.get('kind') in ('full', 'incremental'), 'tipo de fluxo inválido')
    require(isinstance(value.get('guid'), str) and value['guid'].isdigit(), 'GUID inválido')
    require(isinstance(value.get('depth'), int) and 1 <= value['depth'] <= 100000, 'profundidade inválida')
    require(isinstance(value.get('synthetic', False), bool), 'flag sintético inválido')
    if value['kind'] == 'incremental':
        identifier(value['parent'])
        require(isinstance(value.get('from_guid'), str) and value['from_guid'].isdigit(), 'GUID base inválido')
    else:
        require(value.get('parent') is None and value['depth'] == 1, 'base completa inválida')
    return value


def read_metadata(args, snapshot):
    identifier(snapshot)
    data = command(remote(args, ['stream-query']), input_data=query(args, snapshot))[1]
    require(len(data) <= 1048576, 'metadados grandes demais')
    return validate_metadata(json.loads(data.decode()))


def read_recipe(args, snapshot, root):
    synthetic_capability(args)
    data = command(remote(args, ['stream-query']), input_data=query(args, snapshot, 'recipe.json'))[1]
    require(len(data) <= 64 * 1024 * 1024, 'receita grande demais')
    value = json.loads(data.decode())
    require(isinstance(value, list) and 1 <= len(value) <= 100000, 'receita inválida')
    recipe = [validate_metadata(meta) for meta in value]
    require(recipe[-1] == root, 'receita não corresponde ao ponto selecionado')
    validate_chain([(snapshot, 's{:08d}'.format(index), meta) for index, meta in enumerate(recipe)])
    return recipe


def validate_chain(chain):
    require(chain and chain[0][2]['kind'] == 'full', 'cadeia sem base completa')
    for index, (_, _, meta) in enumerate(chain):
        require(meta['dataset'] == chain[0][2]['dataset'] and meta['depth'] == index + 1 and
                meta['dataset_guid'] == chain[0][2]['dataset_guid'], 'cadeia inconsistente')
        if index:
            require(meta['kind'] == 'incremental' and meta['from_guid'] == chain[index - 1][2]['guid'],
                    'GUIDs da cadeia não coincidem')


def backup(args):
    identifier(args.machine)
    require(len(args.machine) <= 64, 'máquina: máximo 64 caracteres')
    identifier(args.dataset, True)
    require(1 <= args.keep <= 10000 and 1 <= args.full_every <= 1024, 'retenção/cadeia inválida')
    private_directory(args.state)
    lock = os.open(str(args.state / 'lock'), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        raise RuntimeError('backup ZFS já está em execução')
    # Keep this descriptor alive until all retention and state changes finish.
    try:
        backup_locked(args)
    finally:
        os.close(lock)


def backup_locked(args):
    active = args.state / 'active.json'
    require(not active.exists(), 'execução interrompida: inspecione active.json e o snapshot preservado antes de liberar o estado')
    capability(args)
    require(zget('type', args.dataset) == 'filesystem', 'este modo requer dataset filesystem')
    require(zget('encryption', args.dataset) == 'off', 'dataset criptografado requer modo raw, ainda não suportado')
    binding = dict(dataset=args.dataset, dataset_guid=zget('guid', args.dataset), host=args.host,
                   repo=args.repo, machine=args.machine)
    state_path = args.state / 'state.json'
    state = json.loads(state_path.read_text()) if state_path.exists() else dict(binding=binding, successes=[])
    require(state['binding'] == binding, 'estado pertence a outro dataset, máquina ou repositório')
    previous = state['successes'][-1] if state['successes'] else None
    parent = None
    if previous and not args.full and (args.synthetic or previous['depth'] < args.full_every):
        status, guid = command([ZFS, 'get', '-Hp', '-o', 'value', 'guid', previous['snapshot']], check=False)
        if status == 0:
            require(guid.decode().strip() == previous['guid'], 'GUID do snapshot base mudou')
            meta = read_metadata(args, previous['backup'])
            require(meta['guid'] == previous['guid'] and meta['dataset'] == args.dataset and
                    meta['depth'] == previous['depth'], 'base no repositório diverge do estado local')
            parent = previous
        else:
            require(not args.synthetic, 'snapshot base ausente; full sintético não inicia releitura completa automática')
            print('Snapshot base indisponível; criando novo fluxo completo.', file=sys.stderr)
    nonce = uuid.uuid4().hex
    stamp = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
    snapname = 'schipsave-stream-' + stamp + '-' + nonce
    snap = args.dataset + '@' + snapname
    tag = 'schipsave-stream-' + hashlib.sha256(json.dumps(binding, sort_keys=True).encode()).hexdigest()[:16]
    transaction = dict(snapshot=snap, tag=tag, stage='creating', binding=binding)
    atomic(active, transaction)
    try:
        command([ZFS, 'snapshot', snap])
        command([ZFS, 'hold', tag, snap])
        guid = zget('guid', snap)
        meta = dict(format=FORMAT, dataset=args.dataset, dataset_guid=binding['dataset_guid'],
                    snapshot_name=snapname, guid=guid, kind='incremental' if parent else 'full',
                    parent=parent['backup'] if parent else None, from_guid=parent['guid'] if parent else None,
                    depth=parent['depth'] + 1 if parent else 1, send_flags=['-c', '-L'],
                    stream_encoding='zfs-records-v1')
        if args.synthetic:
            meta['synthetic'] = True
        meta['source_txg'] = int(zget('createtxg', snap))
        metadata = args.state / ('metadata-' + nonce + '.json')
        atomic(metadata, meta)
        transaction.update(stage='sending', metadata=str(metadata), guid=guid)
        atomic(active, transaction)
        send = [ZFS, 'send', '-c', '-L']
        if parent:
            send += ['-i', parent['snapshot']]
        send += [snap]
        print('ZFS {}: {} (profundidade {})'.format(meta['kind'], snap, meta['depth']), file=sys.stderr)
        options = ['--zfs-records'] + (['--synthetic'] if args.synthetic else [])
        output = command([ENGINE, 'push-stream', args.host, args.repo, args.machine, str(metadata),
                          meta['parent'] or '-'] + options + ['--'] + send)[1].decode()
        values = dict(line.split('=', 1) for line in output.splitlines() if '=' in line)
        backup_name = identifier(values['snapshot'])
        if args.synthetic:
            read_recipe(args, backup_name, meta)
        else:
            saved = read_metadata(args, backup_name)
            require(saved == meta, 'metadados confirmados divergem do envio')
        state['successes'].append(dict(snapshot=snap, guid=guid, backup=backup_name, depth=meta['depth'], tag=tag))
        atomic(state_path, state)
        transaction.update(stage='committed', backup=backup_name)
        atomic(active, transaction)
        # Only successful snapshots recorded by this job are eligible; failures
        # keep their hold indefinitely, independently of the retention count.
        while len(state['successes']) > args.keep:
            old = state['successes'][0]
            require(zget('guid', old['snapshot']) == old['guid'], 'GUID divergente durante retenção')
            command([ZFS, 'release', old['tag'], old['snapshot']])
            command([ZFS, 'destroy', old['snapshot']])
            state['successes'].pop(0)
            atomic(state_path, state)
        metadata.unlink()
        active.unlink()
        sync_directory(args.state)
        print(output, end='')
    except BaseException as error:
        transaction['error'] = str(error)
        atomic(active, transaction)
        # Preserve both snapshot and failure record. An uncatchable kill leaves
        # active.json in place and blocks the next run for explicit inspection.
        os.replace(str(active), str(args.state / ('failed-' + nonce + '.json')))
        sync_directory(args.state)
        raise


@contextmanager
def restore_lease(args):
    request=query(args,args.snapshot,'lease');request=request[:8]+b'\x04'+request[9:]
    lease=subprocess.Popen(remote(args,['stream-query']),stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    try:
        lease.stdin.write(request);lease.stdin.flush()
        require(lease.stdout.readline()==b'1\n','atualize o servidor: lease de restauração indisponível')
        yield
    finally:
        if lease.stdin and not lease.stdin.closed:lease.stdin.close()
        try:lease.wait(timeout=30)
        except subprocess.TimeoutExpired:lease.terminate();lease.wait(timeout=10)
        lease.stdout.close();lease.stderr.close()

def restore(args):
    identifier(args.target, True)
    args.restore_wait = True
    capability(args)
    request=query(args);status,output=command(remote(args,['stream-query']),check=False,input_data=request[:8]+b'\x05'+request[9:])
    require(status==0 and output.strip()==b'1','atualize o servidor para restauração com retomada protegida')
    # Resolve and check the entire chain before creating anything at the target.
    chain, tail, seen, current = [], [], set(), identifier(args.snapshot)
    while current:
        require(current not in seen and len(tail) < 1024, 'cadeia circular ou longa demais')
        seen.add(current)
        meta = read_metadata(args, current)
        if meta.get('synthetic'):
            recipe = read_recipe(args, current, meta)
            chain = [(current, 's{:08d}'.format(index), item) for index, item in enumerate(recipe)]
            break
        tail.append((current, 'stream.bin', meta))
        current = meta['parent']
    chain += list(reversed(tail))
    validate_chain(chain)
    default_state = Path('/var/lib/schipsave/restores') if os.geteuid()==0 else Path.home()/'.local/state/schipsave/restores'
    state_root = Path(os.environ.get('SCHIPSAVE_RESTORE_STATE_DIR',str(default_state)))
    state_root.mkdir(parents=True,exist_ok=True,mode=0o700)
    key=hashlib.sha256(args.target.encode()).hexdigest()
    with (state_root/(key+'.lock')).open('a') as lock,restore_lease(args):
        fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
        state_path=state_root/(key+'.json')
        identity=dict(host=args.host,repo=str(args.repo),point=args.snapshot,target=args.target,
                      guids=[meta['guid'] for _,_,meta in chain])
        exists,_=command([ZFS,'list','-H','-o','name',args.target],check=False)
        saved=json.loads(state_path.read_text()) if state_path.exists() else {}
        require(exists!=0 or saved.get('identity')==identity,'destino existente não pertence a esta restauração; preservado')
        state=dict(identity=identity,completed=0,stage='restoring')
        atomic(state_path,state)
        resumed=0
        for index,(snapshot,selector,meta) in enumerate(chain):
            code,value=command([ZFS,'get','-Hp','-o','value','guid',args.target+'@'+meta['snapshot_name']],check=False)
            if code==0:
                require(value.decode().strip()==meta['guid'],'GUID existente diverge; destino preservado')
                resumed+=1;state['completed']=index+1;atomic(state_path,state);continue
            attempts=0
            while True:
                if index:
                    previous=chain[index-1][2]
                    require(zget('guid',args.target+'@'+previous['snapshot_name'])==previous['guid'],'base de retomada divergente')
                    require(zget('written@'+previous['snapshot_name'],args.target)=='0','destino foi modificado; retomada recusada')
                errors=deque(maxlen=32)
                source=subprocess.Popen(remote(args,['stream-query']),stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
                def collect_errors():
                    for line in iter(source.stderr.readline,b''):errors.append(line[-4096:])
                error_reader=threading.Thread(target=collect_errors);error_reader.daemon=True;error_reader.start()
                receiver=None
                try:
                    source.stdin.write(query(args,snapshot,selector));source.stdin.close()
                    receiver=subprocess.Popen([ZFS,'receive','-u','-o','mountpoint=none','-o','canmount=off',args.target],stdin=source.stdout)
                    source.stdout.close();received=receiver.wait();read=source.wait()
                    error_reader.join();error=b''.join(errors).decode(errors='replace')
                finally:
                    for process in (source,receiver):
                        if process is not None and process.poll() is None:
                            process.terminate()
                            try:process.wait(timeout=5)
                            except subprocess.TimeoutExpired:process.kill();process.wait()
                if received==0 and read==0:break
                transient=read==255 or any(message in error.lower() for message in ('repositório em uso','timeout de transporte','conexão interrompida','connection reset','connection closed'))
                require(transient,'restauração interrompida; destino e estado de retomada preservados: '+error[-1000:])
                attempts+=1;print('Aguardando transporte/repositório; repetindo somente o segmento não confirmado.',file=sys.stderr,flush=True)
                time.sleep(min(attempts,30))
            require(zget('guid',args.target+'@'+meta['snapshot_name'])==meta['guid'],'GUID restaurado diverge do esperado')
            state['completed']=index+1;atomic(state_path,state)
        require(zget('written@'+chain[-1][2]['snapshot_name'],args.target)=='0','destino foi modificado após restauração; preservado')
        state['stage']='complete';atomic(state_path,state)
        print('restore_segments_reused={}'.format(resumed))
    print('Restauração ZFS concluída em {} ({} fluxos); dataset sem montagem automática.'.format(args.target, len(chain)))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest='action')
    for name in ('backup', 'restore'):
        sub = commands.add_parser(name)
        sub.add_argument('--host', default='--local', help='host SSH; padrão: repositório local')
        sub.add_argument('--repo', required=True)
        if name == 'backup':
            sub.add_argument('--machine', required=True)
            sub.add_argument('--dataset', required=True)
            sub.add_argument('--state', type=Path, required=True)
            sub.add_argument('--keep', type=int, default=7)
            sub.add_argument('--full-every', type=int, default=7)
            sub.add_argument('--full', action='store_true')
            sub.add_argument('--no-synthetic', dest='synthetic', action='store_false', default=True,
                             help='modo antigo: cadeia externa e renovação periódica da base')
        else:
            sub.add_argument('--snapshot', required=True)
            sub.add_argument('--target', required=True)
    args = parser.parse_args()
    require(args.action is not None, 'informe backup ou restore')
    def interrupted(number, frame):
        raise RuntimeError('interrompido por sinal ' + str(number))
    signal.signal(signal.SIGTERM, interrupted)
    (backup if args.action == 'backup' else restore)(args)


if __name__ == '__main__':
    try:
        main()
    except (RuntimeError, ValueError, KeyError, OSError) as error:
        print('schipsave-zfs-stream: ' + str(error), file=sys.stderr)
        sys.exit(1)
