#!/usr/bin/python3 -I
import os
import struct
import subprocess
import sys
from uuid import UUID


def invalid():
    sys.exit("Unexpected Apple keybag format.")


uid = sys.argv[1] if len(sys.argv) > 1 else ""
mode = sys.argv[2] if len(sys.argv) > 2 else ""
transfer = sys.stdin.buffer.read(16129)
legacy = mode == "--check-saved" and transfer.startswith(b"DATA")
if legacy:
    raw = transfer
else:
    if not transfer.startswith(b"T2-TOUCHID-KEYBAG-1\n"):
        sys.exit("Export the keybag again from the selected macOS account.")
    header = transfer.split(b"\n", 3)
    if len(header) != 4 or header[1] != uid.encode("ascii") or len(header[2]) != 36:
        sys.exit("The encrypted export does not match the selected macOS UID.")
    try:
        account = UUID(header[2].decode("ascii")).bytes
    except ValueError:
        invalid()
    raw = header[3]

if not 8 <= len(raw) <= 16000 or raw[:4] != b"DATA":
    invalid()

end = 8 + struct.unpack_from(">I", raw, 4)[0]
if end > len(raw):
    invalid()

pos = 8
uuid = None
user = None
while pos < end:
    if pos + 8 > end:
        invalid()
    tag, size = struct.unpack_from(">4sI", raw, pos)
    pos += 8
    if pos + size > end:
        invalid()
    if tag == b"UUID" and uuid is None:
        uuid = raw[pos:pos + size]
        if size != 16 or not any(uuid):
            invalid()
    if tag == b"USID":
        if user is not None or size != 16:
            invalid()
        user = raw[pos:pos + size]
    pos += size
if uuid is None:
    invalid()
if user is None:
    sys.exit("This keybag does not contain a macOS account ID. Make a new USB export using t2-touchid-setup prepare.")
if legacy:
    # The old file lacks a header tying the embedded account ID to the selected UID.
    if not any(user):
        invalid()
    sys.exit(3)
if not any(account) or user != account:
    sys.exit("The selected keybag belongs to a different macOS account.")

if mode == "--load":
    # t2-aks-tool needs a seekable file. Keep the decrypted bag in an anonymous
    # memory file and pass its descriptor only to the helper that loads it.
    with os.fdopen(os.memfd_create("t2-touchid-keybag", os.MFD_CLOEXEC), "wb") as keybag:
        keybag.write(raw)
        keybag.flush()
        fd = keybag.fileno()
        result = subprocess.run(
            ["/usr/libexec/t2-touchid-recovery/t2-aks-tool", "load-keybag", f"/proc/self/fd/{fd}", "1"],
            pass_fds=(fd,),
        )
    sys.exit(result.returncode)

if mode == "--account-out":
    with open(sys.argv[3], "wb") as output:
        output.write(account)

sys.stdout.buffer.write(uuid)
