"""Puts a LibreOffice engine build into Mkoma's Android build, for local testing.

The engine (a 200 MB native library and 17 MB of resources) is far too big to commit, so the app build looks for the
folder android/engine/ (gitignored) and, when it exists, adds its libraries and assets to the app:

    android/engine/jniLibs/<abi>/*.so
    android/engine/assets/**

This script fills that folder from the viewer APK our own LibreOffice build produces (office_engine/README.md). It takes
only the native libraries and the assets, nothing of the viewer's own screens or code.

Usage: python office_engine/spike/unpack_engine.py <LibreOfficeViewer-...apk> [<another apk for another ABI> ...]
   or: python office_engine/spike/unpack_engine.py --libs <a build's android/jniLibs/<abi> folder>
       (replaces only that ABI's libraries, e.g. with a trimmed build's, keeping everything else; the folder's name is
       the ABI)
Then build with the matching Flutter target: `flutter build apk --target-platform android-x64` (emulator) or
`android-arm64` (phones). Delete android/engine/ to go back to a build without the engine.
"""
import os
import shutil
import sys
import zipfile

# The engine ships its own SQLite, which its certificate store (NSS, libsoftokn3.so) needs with that build's symbol
# versions. Mkoma's own SQLite library (from the sqlite3 Dart package) has the same file name, and an app cannot hold two
# files of one name, so the engine's copy is renamed to a name of the SAME LENGTH and every reference to it (its own
# SONAME and the DT_NEEDED entries of the libraries that load it) is rewritten in place: same length, so no offset in
# the ELF file moves. org/libreoffice/kit/LibreOfficeKit.java loads it under the new name.
RENAME = {b'libsqlite3.so': b'liblosqlit.so'}
assert all(len(a) == len(b) for a, b in RENAME.items())

ROOT = os.path.join(os.path.dirname(__file__), '..', '..', 'android', 'engine')


def main(apks):
    root = os.path.abspath(ROOT)
    if os.path.isdir(root):
        shutil.rmtree(root)
    for apk in apks:
        z = zipfile.ZipFile(apk)
        for info in z.infolist():
            n = info.filename
            if n.startswith('lib/') and n.endswith('.so'):
                base = os.path.basename(n).encode()
                new = RENAME.get(base, base).decode()
                dest = os.path.join(root, 'jniLibs', os.path.dirname(n[len('lib/'):]), new)
            elif n.startswith('assets/') and not info.is_dir():
                dest = os.path.join(root, n)
            else:
                continue
            os.makedirs(os.path.dirname(dest), exist_ok=True)
            data = z.read(info)
            if dest.endswith('.so'):
                for old, new in RENAME.items():
                    if data.count(old) > 1:
                        sys.exit(f'{n}: {old!r} appears {data.count(old)} times; expected at most once (a name, not data)')
                    data = data.replace(old, new)
            with open(dest, 'wb') as out:
                out.write(data)
    total = sum(os.path.getsize(os.path.join(d, f)) for d, _, fs in os.walk(root) for f in fs)
    print(f'{root}: {total / 1e6:.0f} MB')


def patched(name, data):
    for old, new in RENAME.items():
        if data.count(old) > 1:
            sys.exit(f'{name}: {old!r} appears {data.count(old)} times; expected at most once (a name, not data)')
        data = data.replace(old, new)
    return data


def replace_libs(folder):
    abi = os.path.basename(os.path.normpath(folder))
    dest_dir = os.path.join(os.path.abspath(ROOT), 'jniLibs', abi)
    if not os.path.isdir(dest_dir):
        sys.exit(f'{dest_dir} does not exist: unpack an APK for {abi} first')
    shutil.rmtree(dest_dir)
    os.makedirs(dest_dir)
    for f in sorted(os.listdir(folder)):
        if not f.endswith('.so'):
            continue
        new = RENAME.get(f.encode(), f.encode()).decode()
        with open(os.path.join(folder, f), 'rb') as src:
            data = patched(f, src.read())
        with open(os.path.join(dest_dir, new), 'wb') as out:
            out.write(data)
    total = sum(os.path.getsize(os.path.join(dest_dir, f)) for f in os.listdir(dest_dir))
    print(f'{dest_dir}: {total / 1e6:.0f} MB')


if __name__ == '__main__':
    if len(sys.argv) < 2:
        sys.exit(__doc__)
    if sys.argv[1] == '--libs' and len(sys.argv) == 3:
        replace_libs(sys.argv[2])
    else:
        main(sys.argv[1:])
