#!/usr/bin/env python3
"""Btrfs snapshots and native incremental streams, without staging dump files."""
import argparse
import datetime
import fcntl
import importlib.machinery
import io
import json
import os
from pathlib import Path
import platform
import re
import signal
import subprocess
import sys
import uuid

# Python 3.6 under LC_ALL=C otherwise fails on Portuguese status messages.
# Keep the original wrappers alive so they cannot close our shared buffers.
_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))

# Share the already-tested native engine transport and durable state helpers.
# Both adapters are shipped together; loading this module executes no ZFS command.
transport = importlib.machinery.SourceFileLoader(
    '_schipsave_stream_transport', str(Path(__file__).resolve().with_name('schipsave-zfs-stream'))).load_module()
require, command, atomic = transport.require, transport.command, transport.atomic
BTRFS = os.environ.get('SCHIPSAVE_BTRFS_BIN', 'btrfs')
FORMAT = 'schipsave-btrfs-stream-v1'
os.environ['LC_ALL'] = 'C'


def valid_uuid(value):
    require(isinstance(value, str) and re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', value),
            'UUID Btrfs inválido')
    return value


def filesystem(path):
    # Some btrfs-progs releases accept only the mountpoint, not a subvolume.
    # Btrfs subvolumes have distinct st_dev values; use the kernel mount table.
    current = Path(path).resolve(strict=True)
    status, data = command([BTRFS, 'filesystem', 'show', str(current)], check=False)
    if status:
        mounts = []
        for line in Path('/proc/self/mountinfo').read_text().splitlines():
            fields = line.split(); separator = fields.index('-')
            mount = Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m.group(1), 8)), fields[4]))
            if mount == current or mount in current.parents:
                mounts.append((len(str(mount)), mount, fields[separator+1]))
        require(mounts, 'ponto de montagem Btrfs não encontrado')
        _, mount, kind = max(mounts, key=lambda m: m[0])
        require(kind == 'btrfs', 'caminho não está montado em Btrfs')
        data = command([BTRFS, 'filesystem', 'show', str(mount)])[1]
    output = data.decode()
    match = re.search(r'\buuid:\s*([0-9a-f-]{36})\b', output, re.I)
    require(match is not None, 'não foi possível identificar o filesystem Btrfs')
    return valid_uuid(match.group(1).lower())


def subvolume(path, readonly=False):
    output = command([BTRFS, 'subvolume', 'show', str(path)])[1].decode()
    fields = dict(line.strip().split(':', 1) for line in output.splitlines() if ':' in line)
    fields = {key: value.strip() for key, value in fields.items()}
    require(fields.get('UUID') != '-', 'top-level Btrfs sem UUID não é suportado; selecione um subvolume com UUID')
    result = dict(uuid=valid_uuid(fields['UUID']), parent_uuid=fields.get('Parent UUID', '-'),
                  received_uuid=fields.get('Received UUID', '-'), generation=fields['Generation'])
    require(result['generation'].isdigit(), 'geração do subvolume inválida')
    if readonly:
        ro = command([BTRFS, 'property', 'get', '-ts', str(path), 'ro'])[1].strip()
        require(ro == b'ro=true', 'snapshot Btrfs precisa permanecer read-only')
    return result


def compressed_flags(mode):
    help_result = subprocess.run([BTRFS, 'send', '--help'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    release = re.match(r'(\d+)\.(\d+)', platform.release())
    supported = bool(release and tuple(map(int, release.groups())) >= (6, 0) and b'--compressed-data' in help_result.stdout)
    if mode == 'always':
        require(supported, '--compressed-data requer Linux 6.0+ e btrfs-progs com protocolo 2')
    return ['--proto', '2', '--compressed-data'] if mode != 'never' and supported else []


def validate_metadata(value):
    require(value.get('format') == FORMAT, 'backup não é fluxo Btrfs nativo')
    for key in ('source_uuid', 'filesystem_uuid', 'snapshot_uuid'):
        valid_uuid(value[key])
    transport.identifier(value['snapshot_name'])
    require(value.get('kind') in ('full', 'incremental'), 'tipo de fluxo inválido')
    require(type(value.get('depth')) is int and 1 <= value['depth'] <= 100000, 'profundidade inválida')
    require(type(value.get('synthetic', False)) is bool, 'flag sintético inválido')
    require(type(value.get('compressed')) is bool, 'compressão de fluxo inválida')
    if value['kind'] == 'incremental':
        transport.identifier(value['parent'])
        valid_uuid(value['from_uuid'])
    else:
        require(value.get('parent') is None and value.get('from_uuid') is None and value['depth'] == 1, 'base completa inválida')
    return value


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


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


def validate_chain(chain):
    require(chain and chain[0][2]['kind'] == 'full', 'cadeia sem base completa')
    for index, (_, _, meta) in enumerate(chain):
        require(meta['source_uuid'] == chain[0][2]['source_uuid'] and
                meta['filesystem_uuid'] == chain[0][2]['filesystem_uuid'] and meta['depth'] == index+1,
                'cadeia inconsistente')
        if index:
            require(meta['kind'] == 'incremental' and meta['from_uuid'] == chain[index-1][2]['snapshot_uuid'],
                    'UUIDs da cadeia não coincidem')


def read_recipe(args, snapshot, root):
    synthetic_capability(args)
    data = command(transport.remote(args, ['stream-query']),
                   input_data=transport.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 checked_snapshot(record, store, source_uuid):
    path = Path(record['snapshot'])
    require(path.parent == store and path.name.startswith('schipsave-stream-') and not path.is_symlink(),
            'snapshot fora do diretório gerenciado')
    info = subvolume(path, readonly=True)
    require(info['uuid'] == record['uuid'] and info['generation'] == record['generation'] and
            info['parent_uuid'] == source_uuid, 'identidade/geração do snapshot mudou')
    return info


def backup(args):
    transport.identifier(args.machine)
    require(len(args.machine) <= 64, 'máquina: máximo 64 caracteres')
    require(1 <= args.keep <= 10000 and 1 <= args.full_every <= 1024, 'retenção/cadeia inválida')
    transport.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)
        backup_locked(args)
    except BlockingIOError:
        raise RuntimeError('backup Btrfs já está em execução')
    finally:
        os.close(lock)


def backup_locked(args):
    active = args.state / 'active.json'
    require(not active.exists(), 'execução interrompida: inspecione active.json e os snapshots preservados')
    transport.capability(args)
    if args.synthetic:
        synthetic_capability(args)
    require(args.subvolume.is_absolute() and args.snapshots.is_absolute(), 'caminhos Btrfs devem ser absolutos')
    source = args.subvolume.resolve(strict=True)
    info = subvolume(source)
    require(not command([BTRFS, 'subvolume', 'list', '-o', str(source)])[1].strip(),
            'subvolumes filhos não são incluídos em snapshots; configure jobs separados')
    store = args.snapshots.resolve()
    require(source != store and source not in store.parents and store not in source.parents,
            'origem e diretório de snapshots precisam estar separados')
    transport.private_directory(args.snapshots)
    require(args.snapshots.resolve(strict=True) == store, 'caminho do diretório de snapshots mudou')
    fs_uuid = filesystem(source)
    require(filesystem(store) == fs_uuid, 'snapshots precisam estar no mesmo filesystem Btrfs da origem')
    flags = compressed_flags(args.compressed_data)
    binding = dict(source=str(source), source_uuid=info['uuid'], filesystem_uuid=fs_uuid,
                   snapshots=str(store), 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 subvolume, 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):
        if Path(previous['snapshot']).exists():
            checked_snapshot(previous, store, info['uuid'])
            meta = read_metadata(args, previous['backup'])
            require(meta['snapshot_uuid'] == previous['uuid'] and meta['source_uuid'] == info['uuid'] and
                    meta['filesystem_uuid'] == fs_uuid 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 ausente; criando nova base completa.', file=sys.stderr)
    nonce = uuid.uuid4().hex
    snapname = 'schipsave-stream-' + datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ') + '-' + nonce
    snapshot = store / snapname
    transaction = dict(snapshot=str(snapshot), stage='creating', binding=binding)
    atomic(active, transaction)
    try:
        command([BTRFS, 'subvolume', 'snapshot', '-r', str(source), str(snapshot)])
        snap = subvolume(snapshot, readonly=True)
        require(snap['parent_uuid'] == info['uuid'], 'snapshot não corresponde à origem')
        meta = dict(format=FORMAT, source_uuid=info['uuid'], filesystem_uuid=fs_uuid,
                    snapshot_name=snapname, snapshot_uuid=snap['uuid'], compressed=bool(flags),
                    kind='incremental' if parent else 'full', parent=parent['backup'] if parent else None,
                    from_uuid=parent['uuid'] if parent else None, depth=parent['depth']+1 if parent else 1)
        if args.synthetic:
            meta['synthetic'] = True
        metadata = args.state / ('metadata-' + nonce + '.json')
        atomic(metadata, meta)
        transaction.update(stage='sending', metadata=str(metadata), uuid=snap['uuid'])
        atomic(active, transaction)
        send = [BTRFS, 'send'] + flags
        if parent:
            send += ['-p', parent['snapshot']]
        send += [str(snapshot)]
        print('Btrfs {}: {} (profundidade {}; compressed-data={})'.format(meta['kind'], snapshot, meta['depth'], bool(flags)), file=sys.stderr)
        output = command([transport.ENGINE, 'push-stream', args.host, args.repo, args.machine, str(metadata),
                          meta['parent'] or '-'] + (['--btrfs-synthetic'] if args.synthetic else []) + ['--'] + send)[1].decode()
        result = dict(line.split('=', 1) for line in output.splitlines() if '=' in line)
        backup_name = transport.identifier(result['snapshot'])
        require(read_metadata(args, backup_name) == meta, 'metadados confirmados divergem do envio')
        if args.synthetic:
            read_recipe(args, backup_name, meta)
        record = dict(snapshot=str(snapshot), uuid=snap['uuid'], generation=snap['generation'],
                      backup=backup_name, depth=meta['depth'])
        checked_snapshot(record, store, info['uuid'])
        state['successes'].append(record)
        atomic(state_path, state)
        transaction.update(stage='committed', backup=backup_name)
        atomic(active, transaction)
        while len(state['successes']) > args.keep:
            old = state['successes'][0]
            # Only recorded successes can be removed; failures never enter here.
            if Path(old['snapshot']).exists():
                checked_snapshot(old, store, info['uuid'])
                command([BTRFS, 'subvolume', 'delete', old['snapshot']])
            state['successes'].pop(0)
            atomic(state_path, state)
        metadata.unlink()
        active.unlink()
        transport.sync_directory(args.state)
        print(output, end='')
    except BaseException as error:
        transaction['error'] = str(error)
        atomic(active, transaction)
        os.replace(str(active), str(args.state / ('failed-' + nonce + '.json')))
        transport.sync_directory(args.state)
        raise


def restore(args):
    # Keep all referenced blocks pinned until every receive has completed.
    with transport.restore_lease(args):
        restore_locked(args)


def restore_locked(args):
    transport.capability(args)
    require(args.target.is_absolute() and not args.target.exists() and not args.target.is_symlink(),
            'restauração exige diretório destino absoluto inexistente')
    filesystem(args.target.parent)
    chain, tail, seen, current = [], [], set(), transport.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)
    if any(meta['compressed'] for _, _, meta in chain):
        version = command([BTRFS, '--version'])[1].decode()
        match = re.search(r'v(\d+)\.(\d+)', version)
        require(match and tuple(map(int, match.groups())) >= (6, 0), 'receber fluxo comprimido requer btrfs-progs 6.0+')
    transport.private_directory(args.target)
    for snapshot, slot, meta in chain:
        require(not (args.target / meta['snapshot_name']).exists(), 'snapshot de destino já existe')
        sender = subprocess.Popen(transport.remote(args, ['stream-query']), stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        receiver = None
        try:
            sender.stdin.write(transport.query(args, snapshot, slot))
            sender.stdin.close()
            receiver = subprocess.Popen([BTRFS, 'receive', str(args.target)], stdin=sender.stdout)
            sender.stdout.close()
            receive_status, read_status = receiver.wait(), sender.wait()
            require(receive_status == 0 and read_status == 0, 'restauração interrompida; destino parcial preservado')
        finally:
            for process in (sender, 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()
        received = subvolume(args.target / meta['snapshot_name'], readonly=True)
        require(received['received_uuid'] == meta['snapshot_uuid'], 'received_uuid diverge do snapshot enviado')
    print('Restauração Btrfs concluída: {} ({} fluxos; snapshots read-only).'.format(args.target / chain[-1][2]['snapshot_name'], 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')
        sub.add_argument('--repo', required=True)
        if name == 'backup':
            sub.add_argument('--machine', required=True)
            sub.add_argument('--subvolume', type=Path, required=True)
            sub.add_argument('--snapshots', type=Path, 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('--compressed-data', choices=('auto', 'always', 'never'), default='auto')
            sub.add_argument('--full', action='store_true')
            sub.add_argument('--no-synthetic', dest='synthetic', action='store_false', default=True,
                             help='usar cadeia externa antiga, com completos periódicos')
        else:
            sub.add_argument('--snapshot', required=True)
            sub.add_argument('--target', type=Path, required=True)
    args = parser.parse_args()
    require(args.action, '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-btrfs-stream: ' + str(error), file=sys.stderr)
        sys.exit(1)
