#!/usr/bin/env python3
"""Inventory-based offline backup; restore only into a NEW staging directory.

Stop all writers first. Inventory JSON: {"paths": ["/absolute/path", ...]}.
List every external data/config/secret/unit path, including symlink targets.
Requires GNU tar with ACL/xattr support. Ownership restoration needs root.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess


def digest(path):
    h = hashlib.sha256()
    with path.open('rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            h.update(block)
    return h.hexdigest()


def within(path, parent):
    return path == parent or parent in path.parents


def inventory(path):
    data = json.loads(path.read_text())
    paths = [Path(p) for p in data['paths']]
    if not paths or len(paths) != len(set(paths)):
        raise ValueError('Inventory must contain unique paths')
    for p in paths:
        if not p.is_absolute() or '..' in p.parts or str(p) == '/' or '\n' in str(p):
            raise ValueError('Use explicit absolute paths, never / or traversal')
        if not p.exists():
            raise ValueError('Missing inventory path: %s' % p)
        if any(p != q and within(p, q) for q in paths):
            raise ValueError('Overlapping inventory paths: %s' % p)
    for base in paths:
        entries = [base]
        if base.is_dir() and not base.is_symlink():
            entries.extend(base.rglob('*'))
        for p in entries:
            if p.is_symlink():
                target = p.resolve(strict=True)
                if not any(within(target, q.resolve()) for q in paths if not q.is_symlink()):
                    raise ValueError('External symlink target missing from inventory: %s -> %s' % (p, target))
            elif not (p.is_file() or p.is_dir()):
                raise ValueError('Special file found; stop writers/remove transient socket: %s' % p)
    return paths


def backup(args):
    paths = inventory(args.inventory)
    if os.path.lexists(args.destination):
        raise ValueError('Backup destination already exists, including symlinks')
    destination = args.destination.resolve()
    if destination.exists() or any(within(destination, p.resolve()) for p in paths):
        raise ValueError('Backup destination must be NEW and outside all inventoried paths')
    destination.mkdir(mode=0o700, parents=False)
    listing = destination / 'paths.json'
    listing.write_text(json.dumps({'paths': [str(p) for p in paths]}, indent=2) + '\n')
    archive = destination / 'offline.tar'
    subprocess.run(['tar', '--acls', '--xattrs', '--numeric-owner', '-cpf', str(archive),
                    '-C', '/', '--'] + [str(p.relative_to('/')) for p in paths], check=True)
    (destination / 'SHA256SUMS').write_text('%s  offline.tar\n%s  paths.json\n' %
                                         (digest(archive), digest(listing)))
    print('Offline backup created; preserve this directory and validate a separate restore.')


def restore(args):
    source = args.backup.absolute()
    checksums = {}
    for line in (source / 'SHA256SUMS').read_text().splitlines():
        match = re.fullmatch(r'([0-9a-f]{64})  (offline\.tar|paths\.json)', line)
        if not match or match[2] in checksums:
            raise ValueError('Backup requires exactly two unique SHA-256 entries')
        checksums[match[2]] = match[1]
    if set(checksums) != {'offline.tar', 'paths.json'}:
        raise ValueError('Missing required backup checksum')
    for name, expected in checksums.items():
        if digest(source / name) != expected:
            raise ValueError('Backup checksum mismatch')
    # Archives are generated by this helper from explicit absolute inventory paths.
    # A separate target avoids overwriting any running installation.
    if os.path.lexists(args.destination):
        raise ValueError('Restore destination already exists, including symlinks')
    target = args.destination.resolve()
    if target.exists():
        raise ValueError('Restore destination must be NEW')
    target.mkdir(mode=0o700, parents=False)
    subprocess.run(['tar', '--acls', '--xattrs', '--numeric-owner', '-xpf',
                    str(source / 'offline.tar'), '-C', str(target)], check=True)
    print('Restored into staging; original absolute paths are below %s' % target)


def main():
    os.umask(0o077)
    p = argparse.ArgumentParser(description=__doc__)
    sub = p.add_subparsers(dest='action', required=True)
    b = sub.add_parser('backup')
    b.add_argument('--inventory', type=Path, required=True)
    b.add_argument('--destination', type=Path, required=True)
    r = sub.add_parser('restore')
    r.add_argument('--backup', type=Path, required=True)
    r.add_argument('--destination', type=Path, required=True)
    args = p.parse_args()
    try:
        (backup if args.action == 'backup' else restore)(args)
    except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as exc:
        p.exit(1, 'Offline backup/restore failed: %s\n' % exc)


if __name__ == '__main__':
    main()
