#!/usr/bin/env python3
"""Decrypt an Armory Manager encrypted backup (.armory) into a plain .zip.

Armory Manager's encrypted backups are not password-protected zips — they are
a small, documented container so the encryption can be real AES-256-GCM
instead of the legacy zip password scheme. This script is the reference
implementation for opening one without the app. It has no ties to the app or
its maker: everything needed is in the file itself plus your password.

Requirements: Python 3.8+ and the `cryptography` package
    (install once with:  python3 -m pip install cryptography)

Usage:
    python3 decrypt-backup.py Armory_Backup_2026-08-25_1030.armory

You will be prompted for the backup password. The output is an ordinary .zip
written next to the input file, containing `armory.db` (a standard SQLite
database) and an `attachments/` folder with your photos and documents.

Container layout (format version 1), all offsets in bytes:

    0   9   magic          ASCII "ARMORYENC"
    9   1   version        0x01
    10  4   iterations     PBKDF2 rounds, unsigned 32-bit big-endian
    14  16  salt           PBKDF2 salt
    30  12  nonce          AES-GCM nonce
    42  16  tag            AES-GCM authentication tag
    58  ..  ciphertext     the zip, encrypted

Key derivation: PBKDF2-HMAC-SHA256 over the UTF-8 password with the salt and
iteration count from the header, producing a 256-bit key. Decryption:
AES-256-GCM with the header's nonce and tag, no associated data.
"""

import getpass
import struct
import sys
from pathlib import Path

try:
    from cryptography.exceptions import InvalidTag
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
    from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
except ImportError:
    sys.exit(
        "The 'cryptography' package is missing.\n"
        "Install it once with:  python3 -m pip install cryptography"
    )

MAGIC = b"ARMORYENC"
VERSION = 1
HEADER_LEN = 9 + 1 + 4 + 16 + 12 + 16


def main() -> None:
    if len(sys.argv) != 2:
        sys.exit(f"Usage: {sys.argv[0]} <backup.armory>")

    src = Path(sys.argv[1])
    data = src.read_bytes()

    if not data.startswith(MAGIC):
        if data[:2] == b"PK":
            sys.exit(
                f"{src.name} is already a plain zip — no password was set. "
                "Any archive tool opens it directly."
            )
        sys.exit(f"{src.name} is not an Armory Manager encrypted backup.")
    if len(data) < HEADER_LEN:
        sys.exit(f"{src.name} is truncated and cannot be read.")

    version = data[9]
    if version != VERSION:
        sys.exit(
            f"{src.name} uses format version {version}; this script "
            f"understands version {VERSION}. Check for a newer copy at "
            "https://armorymanager.app/backups/"
        )

    (iterations,) = struct.unpack(">I", data[10:14])
    salt, nonce, tag = data[14:30], data[30:42], data[42:58]
    ciphertext = data[58:]

    password = getpass.getpass("Backup password: ")

    kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt,
                     iterations=iterations)
    key = kdf.derive(password.encode("utf-8"))

    try:
        # AESGCM wants the tag appended to the ciphertext.
        plain = AESGCM(key).decrypt(nonce, ciphertext + tag, None)
    except InvalidTag:
        sys.exit(
            "Incorrect password (or a damaged file). The backup cannot be "
            "opened without the exact password it was made with — there is "
            "no recovery key."
        )

    dest = src.with_suffix(".zip")
    if dest.exists():
        sys.exit(f"{dest.name} already exists — move it aside and rerun.")
    dest.write_bytes(plain)
    print(f"Decrypted to {dest.name}. It is now an ordinary zip: inside are "
          "armory.db (SQLite) and your attachments.")


if __name__ == "__main__":
    main()
