# -*- coding: utf-8 -*-
"""Dump .app via SpringBoard (bypass app-side RASP). Reuses JS + helpers from dump.py."""
import frida, sys, os, struct, zipfile, time, plistlib
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from dump import JS, macho_crypt_info, HOST, CHUNK

TARGET = "SpringBoard"


def attach_sb(dev):
    print("[*] attaching SpringBoard...", flush=True)
    session = dev.attach(TARGET)
    script = session.create_script(JS)
    script.on('message', lambda m, _d: m['type'] == 'error' and print("[JS] " + m.get('description', ''), flush=True))
    script.load()
    time.sleep(1)
    return session, script


def download(script, app_path, out_dir, app_name):
    subs = script.exports_sync.listFiles(app_path)
    print(f"[*] {len(subs)} entries", flush=True)
    local_app = os.path.join(out_dir, "Payload", app_name)
    os.makedirs(local_app, exist_ok=True)
    total, skipped = 0, []
    for e in subs:
        rel = e['rel']
        if rel.startswith('._') or '/._' in rel or rel.endswith('.DS_Store'):
            continue
        if e['type'] == 10:
            skipped.append(f"{rel} (symlink -> {e.get('target')})")
            continue
        if e['type'] not in (8, 0):
            continue
        remote = f"{app_path}/{rel}"
        try:
            size = script.exports_sync.fileSize(remote)
            if size is None or size < 0:
                size = 0
            local = os.path.join(local_app, *rel.split('/'))
            os.makedirs(os.path.dirname(local), exist_ok=True)
            with open(local, 'wb') as f:
                off = 0
                lastp = 0
                while off < size:
                    n = min(CHUNK, size - off)
                    data = script.exports_sync.readChunk(remote, off, n)
                    if data is None:
                        raise RuntimeError("read null")
                    f.write(data)
                    off += len(data)
                    mb = off >> 20
                    if mb >= lastp + 32:
                        print(f"    {rel}: {mb} MB", flush=True)
                        lastp = mb
            total += size
        except Exception as ex:
            skipped.append(f"{rel} ({type(ex).__name__}: {ex})")
    print(f"[*] downloaded {total/1048576:.1f} MB, skipped {len(skipped)}", flush=True)
    for s in skipped[:30]:
        print("    SKIP:", s, flush=True)
    return local_app


def main():
    app_path = sys.argv[1]
    dm = frida.get_device_manager()
    dev = dm.add_remote_device(HOST)
    app_name = os.path.basename(app_path)
    out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "out")
    os.makedirs(os.path.join(out_dir, "Payload"), exist_ok=True)

    session, script = attach_sb(dev)

    # peek at main binary encryption status
    try:
        with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "appver_cache.txt"), "w") as f:
            pass
    except Exception:
        pass
    exe_name = None
    try:
        # Info.plist may be binary plist - fetch first 4KB is not enough; download it fully first
        local_app = os.path.join(out_dir, "Payload", app_name)
        os.makedirs(local_app, exist_ok=True)
        info_remote = f"{app_path}/Info.plist"
        size = script.exports_sync.fileSize(info_remote)
        data = script.exports_sync.readChunk(info_remote, 0, size)
        with open(os.path.join(local_app, "Info.plist"), 'wb') as f:
            f.write(data)
        pl = plistlib.loads(data)
        exe_name = pl.get('CFBundleExecutable')
        print(f"[*] executable: {exe_name}, ver: {pl.get('CFBundleShortVersionString')} ({pl.get('CFBundleVersion')})", flush=True)
    except Exception as ex:
        print(f"[!] Info.plist: {ex}", flush=True)

    if exe_name:
        try:
            head = script.exports_sync.readChunk(f"{app_path}/{exe_name}", 0, 65536)
            tmp = os.path.join(out_dir, "_head.bin")
            with open(tmp, 'wb') as f:
                f.write(head)
            ci = macho_crypt_info(tmp)
            os.remove(tmp)
            if ci:
                slice_off, cryptoff, cryptsize, cryptid, _ = ci
                print(f"[*] {exe_name}: cryptsize={cryptsize} cryptid={cryptid}", flush=True)
                if cryptid and cryptsize:
                    print("[!] BINARY IS ENCRYPTED - can't pure-copy. Will need memory decrypt.", flush=True)
            else:
                print("[*] binary: not Mach-O or no encryption LC (likely decrypted)", flush=True)
        except Exception as ex:
            print(f"[!] peek: {ex}", flush=True)

    download(script, app_path, out_dir, app_name)
    try:
        session.detach()
    except Exception:
        pass

    ipa = os.path.join(out_dir, app_name[:-4] + ".ipa")
    print(f"[*] zipping -> {ipa}", flush=True)
    with zipfile.ZipFile(ipa, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as z:
        for root, _dirs, files in os.walk(os.path.join(out_dir, "Payload")):
            for fn in files:
                fp = os.path.join(root, fn)
                if fn == "_head.bin":
                    continue
                arc = os.path.relpath(fp, out_dir).replace('\\', '/')
                z.write(fp, arc)
    print(f"=== DONE: {ipa} ({os.path.getsize(ipa)/1048576:.1f} MB) ===", flush=True)


if __name__ == "__main__":
    main()
