#!/usr/bin/env python3
"""Replace CEF's shared Chromium keychain service name with a Nebula-specific one.

CEF/Chromium stores the OSCrypt cookie-encryption key in the login keychain under
"Chromium Safe Storage". That item is often owned by another Chromium-based app,
so unsigned/ad-hoc NebulaBrowser builds get a password prompt on every launch.

The replacement must be the same length as the original (embedded C string).
"""

from __future__ import annotations

import argparse
import sys

OLD = b"Chromium Safe Storage"
NEW = b"NebulaBrowser Storage"

assert len(OLD) == len(NEW), "replacement must be the same length"


def patch(path: str) -> int:
    with open(path, "rb") as handle:
        data = bytearray(handle.read())

    count = data.count(OLD)
    if count == 0:
        if NEW in data:
            print(f"Already patched: {path}")
            return 0
        print(f"ERROR: {OLD!r} not found in {path}", file=sys.stderr)
        return 1

    data = data.replace(OLD, NEW)
    with open(path, "wb") as handle:
        handle.write(data)

    print(f"Patched {count} occurrence(s) in {path}")
    print(f"  {OLD.decode()} -> {NEW.decode()}")
    return 0


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("framework_binary")
    args = parser.parse_args()
    return patch(args.framework_binary)


if __name__ == "__main__":
    sys.exit(main())
