#!/usr/bin/env python3
"""Repackage a full APK with replacement LGPL libraries. Does not sign or install anything."""
import argparse, re, zipfile
from pathlib import Path
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('apk'); p.add_argument('libs'); p.add_argument('output'); a = p.parse_args()
if Path(a.output).exists(): raise ValueError('Choose a new output file')
replaced = []
with zipfile.ZipFile(a.apk) as source, zipfile.ZipFile(a.output,'w') as out:
    for old in source.infolist():
        n = old.filename
        if re.match(r'META-INF/[^/]+\.(SF|RSA|DSA|EC)$',n,re.I) or n.upper() == 'META-INF/MANIFEST.MF': continue
        if old.is_dir(): continue
        data = source.read(n)
        if n.startswith('lib/') and n.endswith('/libusb1.0.so'):
            data = (Path(a.libs)/n.split('/')[1]/'libusb1.0.so').read_bytes(); replaced.append(n)
        info = zipfile.ZipInfo(n,(1980,1,1,0,0,0)); info.external_attr = old.external_attr
        info.compress_type = zipfile.ZIP_STORED if n.startswith('lib/') and n.endswith('.so') else old.compress_type
        out.writestr(info,data)
if len(replaced) != 3:
    Path(a.output).unlink(); raise ValueError('Expected full APK with exactly three libusb ABIs')
print('Replaced three libusb libraries; align and sign with your own key next')
