#!/usr/bin/env python3
"""Sealed weekly backup, inspection, and empty-destination restore."""
import datetime as dt
import gzip
import hashlib
import io
import os
import re
import stat
import sys
import tarfile
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(__file__))
from archiveio import Refused, MAX_FILE, MAX_FILES, MAX_TOTAL, bounded_read, data_files, digest, name_ok, validate_list

MAGIC = b'ARGONIBK'
VERSION = b'\x01'
# An app constant, not a password. The seal hides structure from casual inspection only.
APP_CONSTANT = b'Argoni sealed weekly backup format one 2026'
HEADER = 8 + 1 + 16 + 32
PATTERN = re.compile(r'^Argoni Backup \d{4}-\d{2}-\d{2} \d{4}\.argonibackup$')

def xor(data, salt):
    out = bytearray(len(data))
    for offset in range(0, len(data), 65536):
        block = data[offset:offset+65536]
        stream = hashlib.shake_256(APP_CONSTANT + salt + (offset // 65536).to_bytes(8, 'big')).digest(len(block))
        out[offset:offset+len(block)] = bytes(a ^ b for a, b in zip(block, stream))
    return bytes(out)

def collect(data):
    files = {}
    for rel, path in data_files(data, backup=True):
        with open(path, 'rb') as f:
            files[rel] = bounded_read(f)
    validate_list(files)
    return files

def encode(files):
    raw = io.BytesIO()
    with tarfile.open(fileobj=raw, mode='w', format=tarfile.PAX_FORMAT) as tar:
        for name, content in sorted(files.items()):
            ti = tarfile.TarInfo(name)
            ti.size = len(content)
            ti.mode = 0o600
            ti.mtime = 0
            tar.addfile(ti, io.BytesIO(content))
    plain = raw.getvalue()
    compressed = gzip.compress(plain, mtime=0)
    salt = os.urandom(16)
    return MAGIC + VERSION + salt + hashlib.sha256(plain).digest() + xor(compressed, salt)

def decode(path):
    with open(path, 'rb') as f:
        header = f.read(HEADER)
        if len(header) != HEADER or header[:8] != MAGIC or header[8:9] != VERSION:
            raise Refused('invalid backup header')
        sealed = f.read(MAX_TOTAL + 16 * 1024 * 1024 + 1)
        if len(sealed) > MAX_TOTAL + 16 * 1024 * 1024:
            raise Refused('backup exceeds size cap')
    compressed = xor(sealed, header[9:25])
    try:
        with gzip.GzipFile(fileobj=io.BytesIO(compressed)) as g:
            plain = bounded_read(g, MAX_TOTAL + 16 * 1024 * 1024)
    except (OSError, EOFError) as e:
        raise Refused('invalid compressed backup: %s' % e)
    if hashlib.sha256(plain).digest() != header[25:57]:
        raise Refused('backup integrity mismatch')
    files, seen, total = {}, set(), 0
    try:
        with tarfile.open(fileobj=io.BytesIO(plain), mode='r:') as tar:
            for member in tar:
                if not member.isfile():
                    raise Refused('backup contains a link or special file')
                name_ok(member.name, seen)
                if len(files) >= MAX_FILES or member.size > MAX_FILE or total + member.size > MAX_TOTAL:
                    raise Refused('backup exceeds 20,000 files, 64 MiB per file or 512 MiB total')
                content = bounded_read(tar.extractfile(member))
                total += len(content)
                files[member.name] = content
    except (tarfile.TarError, OSError, EOFError) as e:
        raise Refused('invalid backup tar: %s' % e)
    validate_list(files)
    return files

def make(folder, outdir):
    if not os.path.isdir(outdir):
        raise Refused('output folder does not exist')
    files = collect(os.path.join(folder, 'data'))
    name = 'Argoni Backup %s.argonibackup' % dt.datetime.now().strftime('%Y-%m-%d %H%M')
    path = os.path.join(outdir, name)
    payload = encode(files)
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(fd, 'wb') as f:
        f.write(payload)
    print(path)

def old(outdir):
    names = []
    for name in os.listdir(outdir):
        path = os.path.join(outdir, name)
        if PATTERN.fullmatch(name) and os.path.isfile(path) and not os.path.islink(path):
            with open(path, 'rb') as f:
                h = f.read(HEADER)
            if len(h) == HEADER and h[:9] == MAGIC + VERSION:
                names.append(name)
    for name in sorted(names, reverse=True)[4:]:
        print(os.path.join(outdir, name))

def restore(path, dest):
    files = decode(path)
    if os.path.islink(dest) or (os.path.exists(dest) and (not os.path.isdir(dest) or os.listdir(dest))):
        raise Refused('restore destination must be new or empty')
    # All archive checks have completed before the first write.
    os.makedirs(dest, exist_ok=True)
    data = os.path.join(dest, 'data')
    os.mkdir(data)
    for name, content in sorted(files.items()):
        target = os.path.join(data, *name.split('/'))
        os.makedirs(os.path.dirname(target), exist_ok=True)
        fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, 'wb') as f:
            f.write(content)
    print(dest)

def main(args):
    try:
        if len(args) == 2 and args[0] == '--old':
            old(args[1])
        elif len(args) == 2 and args[0] == '--check':
            files = decode(args[1])
            print('OK %d files' % len(files))
        elif len(args) == 3 and args[0] == 'restore':
            restore(args[1], args[2])
        elif len(args) == 2:
            make(*args)
        else:
            raise Refused('usage: backup FOLDER OUTDIR | backup --old OUTDIR | backup --check FILE | backup restore FILE DEST')
        return 0
    except (Refused, OSError, ValueError) as e:
        print('REFUSED %s' % e, file=sys.stderr)
        return 3
if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
