#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$0")/../.."

platform="${1:-}"
cache_root="${ZYRYN_CUSTOM_VLCKIT_DIR:-$PWD/.appstore-cache/vlckit-3.6.0-c73b779f-dd8bfdba}"

case "$platform" in
ios)
  name="MobileVLCKit"
  destination="ios/Pods/MobileVLCKit"
  ;;
tvos)
  name="TVVLCKit"
  destination="tvos/Pods/TVVLCKit"
  ;;
*)
  echo "usage: $0 <ios|tvos>" >&2
  exit 64
  ;;
esac

source_package="$cache_root/$platform"
if [ ! -d "$source_package/$name.xcframework" ]; then
  echo "[appstore] custom $name is missing from $source_package" >&2
  echo "[appstore] build it first with: bash scripts/appstore/build_custom_vlckit.sh $platform" >&2
  exit 1
fi

ruby scripts/appstore/lib/verify_custom_vlckit.rb "$platform" "$source_package"

staging="${destination}.zyryn-custom-$$"
if [ -e "$staging" ]; then
  echo "[appstore] refusing existing staging path: $staging" >&2
  exit 1
fi
trap 'rm -rf "$staging"' EXIT
mkdir -p "$staging"
/usr/bin/ditto "$source_package/$name.xcframework" "$staging/$name.xcframework"
/usr/bin/ditto "$source_package/COPYING.txt" "$staging/COPYING.txt"
/usr/bin/ditto "$source_package/provenance.json" "$staging/provenance.json"

rm -rf "$destination"
mv "$staging" "$destination"
trap - EXIT

ruby scripts/appstore/lib/verify_custom_vlckit.rb "$platform" "$destination"

# CocoaPods generated iOS's XCFramework selector from the stock binary before
# this App Store-only swap. Regenerate that workspace-local selector from the
# verified custom Info.plist; deployment mode prevents lockfile/spec changes
# and the second verifier catches any attempt to restore or alter the package.
# flutter-tvos owns its separate plugin/Pods preparation and may not have
# generated its tvOS plugin list yet at the source-only preflight, so its
# already-generated selector is checked below without rerunning CocoaPods here.
if [ "$platform" = "ios" ]; then
  (
    cd "$platform"
    COCOAPODS_DISABLE_STATS=true pod install --deployment --no-repo-update
  )
  ruby scripts/appstore/lib/verify_custom_vlckit.rb "$platform" "$destination"
fi

support_script="$platform/Pods/Target Support Files/$name/$name-xcframeworks.sh"
ruby scripts/appstore/lib/verify_cocoapods_xcframework_integration.rb \
  "$destination/$name.xcframework" "$support_script"
echo "[appstore] staged privacy-safe custom $name into $destination"
