#!/bin/sh
set -e

if [ -z "${JAVA_HOME:-}" ]; then
    JDK_HOME="$(/usr/libexec/java_home -v 21 2>/dev/null || true)"

    if [ -z "$JDK_HOME" ]; then
        for candidate in \
            "$HOME/Applications/Android Studio.app/Contents/jbr/Contents/Home" \
            "/Applications/Android Studio.app/Contents/jbr/Contents/Home"
        do
            if [ -x "$candidate/bin/java" ]; then
                JDK_HOME="$candidate"
                break
            fi
        done
    fi

    if [ -n "$JDK_HOME" ]; then
        export JAVA_HOME="$JDK_HOME"
        export PATH="$JAVA_HOME/bin:$PATH"
    fi
fi

if [ -n "${SRCROOT:-}" ]; then
    REPO_ROOT="$SRCROOT/.."
else
    SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
    REPO_ROOT="$SCRIPT_DIR/.."
fi

cd "$REPO_ROOT"
. "$REPO_ROOT/scripts/yokan-version.sh"
./gradlew :composeApp:embedAndSignAppleFrameworkForXcode --stacktrace --console=plain

# Bundle libmpv beside the app so kmp-mpv's dynamic bridge can resolve it.
# The published archive currently labels its arm64 binaries as device-only,
# but the binaries are also usable by the arm64 simulator after rewriting the
# Mach-O platform load command, matching the embedded JVM runtime strategy.
case "${PLATFORM_NAME:-}" in
    iphoneos|iphonesimulator)
        MPV_ROOT="${YOKAN_KMP_MPV_ROOT:-$REPO_ROOT/vendor/kmp-mpv}"
        "$MPV_ROOT/scripts/prepare-media-kit-ios.sh"
        MPV_FRAMEWORKS="$MPV_ROOT/build/media-kit-mpv/ios"
        APP_FRAMEWORKS="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
        mkdir -p "$APP_FRAMEWORKS"

        for xcframework in "$MPV_FRAMEWORKS"/*.xcframework; do
            framework_name="$(basename "$xcframework" .xcframework)"
            source_framework="$xcframework/ios-arm64/$framework_name.framework"
            if [ -d "$source_framework" ]; then
                destination_framework="$APP_FRAMEWORKS/$framework_name.framework"
                rm -rf "$destination_framework"
                ditto "$source_framework" "$destination_framework"

                if [ "${PLATFORM_NAME:-}" = "iphonesimulator" ]; then
                    binary="$destination_framework/$framework_name"
                    patched="${binary}.iossim"
                    /usr/bin/xcrun vtool \
                        -set-build-version iossim "${IPHONEOS_DEPLOYMENT_TARGET:-15.0}" "${SDK_VERSION:-26.0}" \
                        -replace -output "$patched" "$binary"
                    /bin/mv "$patched" "$binary"
                fi

                signing_identity="${EXPANDED_CODE_SIGN_IDENTITY:--}"
                codesign --force --sign "$signing_identity" \
                    --preserve-metadata=identifier,entitlements \
                    "$destination_framework"
            fi
        done
        ;;
esac
