#!/bin/sh
# Build an unsigned iOS .ipa for sideloading (AltStore/SideStore re-sign on install).
# Used by the GitHub and Forgejo release workflows and by Codemagic.
#
# Usage:
#   scripts/build-ios-unsigned-ipa.sh
#
# Environment:
#   YOKAN_SIDELOAD_RUNTIME  YES (default) embeds the signed Java 21 runtime and
#                           M-Extension-Server via iosApp/PrepareExtensionRuntime.sh;
#                           NO builds without the embedded extension runtime.
#   CONFIGURATION           Xcode configuration, default Release.
#   YOKAN_VERSION           Release version/tag; defaults to version.xcconfig.
#   YOKAN_VERSION_CODE      Optional positive platform build number override.
set -eu

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$SCRIPT_DIR/.."
. "$SCRIPT_DIR/yokan-version.sh"
CONFIGURATION="${CONFIGURATION:-Release}"
SIDELOAD="${YOKAN_SIDELOAD_RUNTIME:-YES}"
case "$SIDELOAD" in
    YES) SIDELOAD_ENABLED=1 ;;
    NO) SIDELOAD_ENABLED=0 ;;
    *) echo "error: YOKAN_SIDELOAD_RUNTIME must be YES or NO" >&2; exit 2 ;;
esac
DERIVED_DATA="$REPO_ROOT/build/ios-ipa/DerivedData"
OUTPUT_DIR="$REPO_ROOT/build/ios-ipa/dist"
PRODUCTS_DIR="$DERIVED_DATA/Build/Products/$CONFIGURATION-iphoneos"

echo "==> Building unsigned $CONFIGURATION iosApp (sideload runtime: $SIDELOAD)"
xcodebuild \
    -project "$REPO_ROOT/iosApp/iosApp.xcodeproj" \
    -scheme iosApp \
    -configuration "$CONFIGURATION" \
    -destination 'generic/platform=iOS' \
    -derivedDataPath "$DERIVED_DATA" \
    YOKAN_SIDELOAD_RUNTIME="$SIDELOAD" \
    YOKAN_SIDELOAD_RUNTIME_ENABLED="$SIDELOAD_ENABLED" \
    YOKAN_VERSION="$YOKAN_VERSION" \
    MARKETING_VERSION="$YOKAN_VERSION" \
    CURRENT_PROJECT_VERSION="$YOKAN_VERSION_CODE" \
    CODE_SIGNING_ALLOWED=NO \
    CODE_SIGNING_REQUIRED=NO \
    CODE_SIGN_IDENTITY="" \
    build

APP_PATH="$(/bin/ls -d "$PRODUCTS_DIR"/*.app 2>/dev/null | head -n 1 || true)"
if [ -z "$APP_PATH" ]; then
    echo "error: no .app produced under $PRODUCTS_DIR" >&2
    exit 1
fi

if [ "$SIDELOAD" = "YES" ]; then
    for required in \
        "$APP_PATH/Frameworks/OpenJDKRuntime.framework/OpenJDKRuntime" \
        "$APP_PATH/MExtensionServer.jar"
    do
        if [ ! -e "$required" ]; then
            echo "error: sideload runtime asset missing from app bundle: $required" >&2
            exit 1
        fi
    done
fi

VERSION="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$APP_PATH/Info.plist" 2>/dev/null || echo dev)"
TAG="v$VERSION"
IPA_PATH="$OUTPUT_DIR/Yokan-$TAG-ios-unsigned.ipa"

echo "==> Packaging $IPA_PATH"
STAGE_DIR="$REPO_ROOT/build/ios-ipa/stage"
rm -rf "$STAGE_DIR" "$IPA_PATH"
mkdir -p "$STAGE_DIR/Payload" "$OUTPUT_DIR"
/usr/bin/ditto "$APP_PATH" "$STAGE_DIR/Payload/$(basename "$APP_PATH")"
(cd "$STAGE_DIR" && /usr/bin/ditto -c -k --norsrc --keepParent Payload "$IPA_PATH")
rm -rf "$STAGE_DIR"

/bin/ls -lh "$IPA_PATH"
echo "==> Done. Install with AltStore/SideStore (they re-sign the unsigned bundle)."
