#!/bin/bash -e

# Downloads the Airbridge iOS SDK XCFramework of `ios_version` in
# airbridge_sdk.json, verifies its checksum, and extracts it to
# ios/Airbridge.xcframework so that it can be consumed through
# `s.vendored_frameworks` in the podspec.
#
# Invoked from three places:
#   1. npm `prepack` (with --force) — so the XCFramework ships inside the npm
#      package and the S3 tarball produced by `npm pack` in CI. This is what
#      consumers rely on.
#   2. podspec `prepare_command` (with --if-missing) — CocoaPods runs this for
#      `:path` pods, which is how React Native autolinking registers the module,
#      but ONLY when it installs the pod (verified against CocoaPods 1.16.2). It
#      is a first-install safety net, not a repair mechanism, and it never
#      replaces an internal build that is already there.
#   3. qa/ios/Podfile — on every `pod install` of the QA application, with the
#      internal build of qa/airbridge_qa.json when one is pinned.
#
# The SDK variant (normal vs restricted) follows the package name in
# package.json, which script/ChangeRestricted.sh renames.
#
# The expected checksum is the one the iOS SDK team publishes for Swift Package
# Manager in the deployment repository's Package.swift at the `ios_version` tag.
# It comes from a different source than the archive itself, and it guarantees
# that CocoaPods consumers get the same binary as Swift Package Manager ones.
#
# QA only: AIRBRIDGE_IOS_INTERNAL_VERSION=<build> fetches an internal build from
# sdk-internal.airbridge.io instead (qa/ios/Podfile sets it from
# qa/airbridge_qa.json). Internal builds have no published checksum, so none is
# verified. The stamp records the internal version, so a later run without the
# variable — `npm pack` included — replaces it with the release build.
#
# The stamp records what was downloaded, not the integrity of the files on disk,
# so --force re-downloads even when the stamp matches. `prepack` passes it so
# that a locally modified XCFramework never ships without the checksum check.
#
# The XCFramework is vendored exactly as published — see the note further down
# before considering any size optimisation on it.

# Errexit comes from the shebang, which a "sh <file>" invocation ignores.
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

SDK_JSON="$ROOT_DIR/airbridge_sdk.json"
IOS_VERSION="$(perl -ne '/"ios_version"\s*:\s*"([^"]*)"/ && print $1' "$SDK_JSON")"
if grep -qE '"name": *"airbridge-react-native-sdk-restricted"' "$ROOT_DIR/package.json"; then
    IOS_SDK_NAME="airbridge-ios-sdk-restricted"
else
    IOS_SDK_NAME="airbridge-ios-sdk"
fi

XCFRAMEWORK_DIR="$SCRIPT_DIR/Airbridge.xcframework"
STAMP_FILE="$SCRIPT_DIR/Airbridge.xcframework.stamp"

# --if-missing: used by the podspec `prepare_command`, which runs without the QA
# variable. Without this, it would silently replace an internal build that
# qa/ios/Podfile has just put in place with the release build, because
# CocoaPods installs the pod after evaluating the Podfile. Only an internal
# build is kept this way: any other framework still goes through the stamp
# check below, so one of another ios_version or variant is replaced.
if [ "${1:-}" = "--if-missing" ] && [ -f "$XCFRAMEWORK_DIR/Info.plist" ]; then
    case "$(cat "$STAMP_FILE" 2>/dev/null)" in
        internal:*)
            echo "[Airbridge] Airbridge.xcframework internal build already present, skipping download"
            exit 0
            ;;
    esac
fi

if [ -z "$IOS_VERSION" ]; then
    echo "[Airbridge] ERROR: ios_version not found in $SDK_JSON" >&2
    exit 1
fi

ZIP_URL="https://sdk-download.airbridge.io/${IOS_SDK_NAME}/${IOS_VERSION}/Airbridge.zip"
ARCHIVE_DIR="Airbridge"
EXPECTED_STAMP="public:${IOS_SDK_NAME}:${IOS_VERSION}"

INTERNAL_VERSION="${AIRBRIDGE_IOS_INTERNAL_VERSION:-}"
if [ -n "$INTERNAL_VERSION" ]; then
    # Internal builds of both variants live under build/airbridge-ios-sdk/; the
    # restricted one is AirbridgeRestricted.zip with an AirbridgeRestricted/ root.
    if [ "$IOS_SDK_NAME" = "airbridge-ios-sdk-restricted" ]; then
        ARCHIVE_DIR="AirbridgeRestricted"
    fi
    ZIP_URL="https://sdk-internal.airbridge.io/build/airbridge-ios-sdk/${INTERNAL_VERSION}/${ARCHIVE_DIR}.zip"
    IOS_VERSION="$INTERNAL_VERSION (internal)"
    EXPECTED_STAMP="internal:${IOS_SDK_NAME}:${INTERNAL_VERSION}"
fi

# Skip only when the extracted XCFramework is actually there. Checking the
# directory alone is not enough: a partially removed tree leaves the directory
# skeleton behind, and a stale stamp would then mark an empty framework as good.
if [ "${1:-}" != "--force" ] && [ -f "$XCFRAMEWORK_DIR/Info.plist" ] && [ -f "$STAMP_FILE" ] && [ "$(cat "$STAMP_FILE")" = "$EXPECTED_STAMP" ]; then
    echo "[Airbridge] Airbridge.xcframework $IOS_SDK_NAME $IOS_VERSION already present, skipping download"
    exit 0
fi

sha256_of() {
    if command -v shasum >/dev/null 2>&1; then
        shasum -a 256 "$1" | awk '{print $1}'
    else
        sha256sum "$1" | awk '{print $1}'
    fi
}

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT
ZIP_PATH="$TMP_DIR/Airbridge.zip"

if [ -z "$INTERNAL_VERSION" ]; then
    PACKAGE_SWIFT_URL="https://raw.githubusercontent.com/ab180/${IOS_SDK_NAME}-deployment/${IOS_VERSION}/Package.swift"
    echo "[Airbridge] Fetching the checksum of $IOS_SDK_NAME $IOS_VERSION..."
    curl -fsSL --retry 3 -o "$TMP_DIR/Package.swift" "$PACKAGE_SWIFT_URL"
    EXPECTED_CHECKSUM="$(perl -ne '/checksum:\s*"([0-9a-f]{64})"/ && print $1' "$TMP_DIR/Package.swift")"
    if [ -z "$EXPECTED_CHECKSUM" ]; then
        echo "[Airbridge] ERROR: checksum not found in $PACKAGE_SWIFT_URL" >&2
        exit 1
    fi
fi

echo "[Airbridge] Downloading $IOS_SDK_NAME $IOS_VERSION..."
curl -fSL --retry 3 -o "$ZIP_PATH" "$ZIP_URL"

if [ -z "$INTERNAL_VERSION" ]; then
    ACTUAL_CHECKSUM="$(sha256_of "$ZIP_PATH")"
    if [ "$ACTUAL_CHECKSUM" != "$EXPECTED_CHECKSUM" ]; then
        echo "[Airbridge] ERROR: checksum mismatch for $IOS_SDK_NAME $IOS_VERSION" >&2
        echo "[Airbridge]   url:      $ZIP_URL" >&2
        echo "[Airbridge]   expected: $EXPECTED_CHECKSUM ($PACKAGE_SWIFT_URL)" >&2
        echo "[Airbridge]   actual:   $ACTUAL_CHECKSUM" >&2
        exit 1
    fi
fi

echo "[Airbridge] Extracting Airbridge.xcframework..."
unzip -q -o "$ZIP_PATH" -d "$TMP_DIR"

EXTRACTED="$TMP_DIR/$ARCHIVE_DIR/Airbridge.xcframework"
if [ ! -f "$EXTRACTED/Info.plist" ]; then
    echo "[Airbridge] ERROR: Airbridge.xcframework not found inside the archive" >&2
    echo "[Airbridge]   expected: $ARCHIVE_DIR/Airbridge.xcframework/Info.plist" >&2
    exit 1
fi

# The XCFramework is used EXACTLY as the vendor published it. Do not strip
# anything from it: removing the dSYM bundles invalidates the vendor's
# signature ("a sealed resource is missing or invalid"). Integrity therefore
# rests on the sha256 check above, and the framework Xcode sees is
# byte-identical to the published one.

# Drop the stamp first: if the replacement below is interrupted, a stamp left
# next to a partial framework would make the next run accept it.
rm -f "$STAMP_FILE"
rm -rf "$XCFRAMEWORK_DIR"
mv "$EXTRACTED" "$XCFRAMEWORK_DIR"
printf '%s' "$EXPECTED_STAMP" > "$STAMP_FILE"

echo "[Airbridge] Airbridge.xcframework $IOS_SDK_NAME $IOS_VERSION ready at $XCFRAMEWORK_DIR"
