#!/bin/bash
# The repacked iPhoneOS18.6 SDK has incomplete .tbd stubs (Swift overlay symbols are missing).
# Given a failed ld64 log, this asks the iPhone which library really exports each undefined symbol,
# records the answers in tools/sdk-extra-symbols.txt and patches those stubs (locally and in the phone's copy).
# Usage: tools/resolve-undefined build/build.log      (no argument: re-apply the recorded list)
set -euo pipefail
cd "$(dirname "$0")/.."

IPHONE=${IPHONE:-mobile@192.168.1.94}
KEY=${IPHONE_KEY:-$HOME/.ssh/iphone_key}
SWIFT=${SWIFT:-$HOME/.local/opt/swift/usr/bin}
SDK=${SDK:-$HOME/.local/opt/dl/sdk18/iPhoneOS18.6.sdk}
REMOTE=/var/mobile/mulberry-build
LIST=tools/sdk-extra-symbols.txt
touch "$LIST"
ssh_=(ssh -i "$KEY" -o BatchMode=yes -o ConnectTimeout=10 "$IPHONE")
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT

if [ $# -gt 0 ]; then
    syms=$(grep -E '^  "' "$1" | sed -E 's/^  "(.*)", referenced from:/\1/' | sort -u | grep -v '^___isPlatformVersionAtLeast$' || true)
    if [ -n "$syms" ]; then
        # dlopen every framework and Swift overlay, then dladdr each symbol to find its image.
        {
            echo '#include <dlfcn.h>'
            echo '#include <stdio.h>'
            echo 'int main(void){'
            for f in $(ls "$SDK/System/Library/Frameworks" | sed -n 's/\.framework$//p'); do
                echo "  dlopen(\"/System/Library/Frameworks/$f.framework/$f\", RTLD_LAZY);"
            done
            for d in "$SDK"/usr/lib/swift/libswift*.tbd; do
                echo "  dlopen(\"/usr/lib/swift/$(basename "$d" .tbd).dylib\", RTLD_LAZY);"
            done
            echo '  const char *s[] = {'
            for s in $syms; do echo "    \"${s#_}\","; done
            echo '  };'
            echo '  for (unsigned i = 0; i < sizeof s / sizeof *s; i++) {'
            echo '    void *p = dlsym(RTLD_DEFAULT, s[i]); Dl_info d = {0};'
            echo '    if (p && dladdr(p, &d)) printf("%s\t_%s\n", d.dli_fname, s[i]);'
            echo '    else fprintf(stderr, "not on device: %s\n", s[i]);'
            echo '  }'
            echo '  return 0;'
            echo '}'
        } > "$work/probe.c"
        "$SWIFT/clang" -target arm64-apple-ios17.0 -isysroot "$SDK" -c "$work/probe.c" -o "$work/probe.o"
        tools/phone-ld -o "$work/probe" "$work/probe.o"
        scp -q -i "$KEY" "$work/probe" "$IPHONE:$REMOTE/probe"
        "${ssh_[@]}" "cd $REMOTE && ldid -S probe && ./probe; rm -f probe" >> "$LIST"
        sort -u -o "$LIST" "$LIST"
    fi
fi

# Patch the local SDK stubs (idempotent, between marker comments) and copy the changed ones to the phone.
python3 tools/patch-tbd.py "$LIST" "$SDK" > "$work/changed"
if [ -s "$work/changed" ]; then
    (cd "$SDK/.." && sed "s|^|$(basename "$SDK")/|" "$work/changed" | tar -cf - -T -) | "${ssh_[@]}" "cd $REMOTE && tar -xf -"
fi
echo "patched $(wc -l < "$work/changed") stub(s) with $(wc -l < "$LIST") symbol(s)"
