#!/bin/bash
# Copy ffmpeg.framework into Instagram.app so dlopen() can load it (iOS blocks
# loading dylibs from outside the app bundle with EACCES).

set -e

# Source path: where the package installed the framework
if [ -d "/var/jb/Library/Application Support/ffmpeg.framework" ]; then
    SOURCE="/var/jb/Library/Application Support/ffmpeg.framework"
elif [ -d "/Library/Application Support/ffmpeg.framework" ]; then
    SOURCE="/Library/Application Support/ffmpeg.framework"
else
    echo "Theta postinst: ffmpeg.framework not found, skipping copy."
    exit 0
fi

# Find Instagram.app (rootful and rootless paths)
INSTA_PATHS=""
for base in /var/containers/Bundle/Application "/var/jb/var/containers/Bundle/Application"; do
    [ ! -d "$base" ] && continue
    while IFS= read -r -d '' app; do
        INSTA_PATHS="$INSTA_PATHS $app"
    done < <(find "$base" -maxdepth 2 -name "Instagram.app" -type d -print0 2>/dev/null)
done

for INSTA_APP in $INSTA_PATHS; do
    DEST="$INSTA_APP/ffmpeg.framework"
    # Remove existing so we don't leave stale libs after upgrades
    rm -rf "$DEST"
    echo "Theta postinst: copying ffmpeg.framework into Instagram.app..."
    cp -R "$SOURCE" "$DEST"
    chmod -R 755 "$DEST"
    echo "Theta postinst: done for $INSTA_APP"
done

if [ -z "$INSTA_PATHS" ]; then
    echo "Theta postinst: Instagram.app not found. Install/reinstall Theta after Instagram is installed to enable AV1/reel transcoding."
fi

exit 0
