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

# Replaces only Mpv.xcframework inside a workspace-local staged media-kit
# plugin package. It deliberately refuses generated links that still point at
# the global pub cache, keeping direct/debug builds unchanged.

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

platform="${1:-}"
package_root="${2:-}"
cache_root="${ZYRYN_CUSTOM_LIBMPV_DIR:-$PWD/.appstore-cache/libmpv-0.36.0-media-kit-v0.6.0}"

case "$platform" in
ios | macos) ;;
*)
  echo "usage: $0 <ios|macos> <staged-media-kit-package-root>" >&2
  exit 64
  ;;
esac
if [ -z "$package_root" ]; then
  echo "usage: $0 <ios|macos> <staged-media-kit-package-root>" >&2
  exit 64
fi

package_root="$(cd "$package_root" && pwd -P)"
case "$package_root" in
"$PWD"/ios/*/.zyryn-appstore-stage-*/* | \
  "$PWD"/ios/.symlinks/.zyryn-appstore-stage-*/* | \
  "$PWD"/macos/Flutter/ephemeral/.zyryn-appstore-stage-*/*) ;;
*)
  echo "[appstore] refusing to modify non-staged media-kit package: $package_root" >&2
  exit 1
  ;;
esac

source_package="$cache_root/$platform"
destination="$package_root/$platform/Frameworks/Mpv.xcframework"
if [ ! -d "$source_package/Mpv.xcframework" ]; then
  echo "[appstore] custom libmpv is missing from $source_package" >&2
  echo "[appstore] build it first with: bash scripts/appstore/build_custom_libmpv.sh $platform" >&2
  exit 1
fi
if [ ! -d "$(dirname "$destination")" ]; then
  echo "[appstore] staged media-kit Frameworks directory not found: $(dirname "$destination")" >&2
  exit 1
fi

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

staging="${destination}.zyryn-custom-$$"
verification="$(mktemp -d -t zyryn-libmpv-stage-verify)"
cleanup_stage() {
  rm -rf "$staging" "$verification"
}
trap cleanup_stage EXIT
/usr/bin/ditto "$source_package/Mpv.xcframework" "$staging"
rm -rf "$destination"
mv "$staging" "$destination"

/usr/bin/ditto "$destination" "$verification/Mpv.xcframework"
/usr/bin/ditto "$source_package/COPYING.LGPL-2.1.txt" \
  "$verification/COPYING.LGPL-2.1.txt"
/usr/bin/ditto "$source_package/Copyright.txt" "$verification/Copyright.txt"
/usr/bin/ditto "$source_package/provenance.json" "$verification/provenance.json"
ruby scripts/appstore/lib/verify_custom_libmpv.rb "$platform" "$verification"

# Retain the exact notices and source identity beside the staged native input.
# The user-visible copy/source offer is published at zyryn.com/open-source.
/usr/bin/ditto "$source_package/COPYING.LGPL-2.1.txt" \
  "$package_root/COPYING.libmpv-LGPL-2.1.txt"
/usr/bin/ditto "$source_package/Copyright.txt" "$package_root/Copyright.libmpv.txt"
/usr/bin/ditto "$source_package/provenance.json" "$package_root/libmpv-provenance.json"

trap - EXIT
rm -rf "$verification"
echo "[appstore] staged privacy-safe custom libmpv into $destination"
