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

script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
if [[ $# -ne 2 ]]; then
  echo "usage: $0 <staging-dir> <ios|ios,tvos>" >&2
  exit 64
fi
case "$2" in
  ios)
    export BEAM_VLCKIT_PLATFORMS=ios
    export BEAM_VLCKIT_OUTPUT_BASENAME=output-ios
    tag_scope=ios
    ;;
  ios,tvos)
    export BEAM_VLCKIT_PLATFORMS=ios,tvos
    export BEAM_VLCKIT_OUTPUT_BASENAME=output-apple
    tag_scope=apple
    ;;
  *)
    echo "candidate platforms must be ios or ios,tvos" >&2
    exit 64
    ;;
esac
# shellcheck source=common.sh
source "$script_dir/common.sh"

beam_assert_work_dir
trap beam_release_canonical_lock EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
beam_acquire_canonical_lock

staging=$1
if beam_platform_selected ios; then
  [[ -d "$staging/frameworks/MobileVLCKit.xcframework" ]] || beam_die "missing iOS framework"
fi
if beam_platform_selected tvos; then
  [[ -d "$staging/frameworks/TVVLCKit.xcframework" ]] || beam_die "missing tvOS framework"
fi

tag="beam-vlckit-$tag_scope-$BEAM_VLCKIT_VERSION-$BEAM_CANDIDATE_REVISION"
asset_base=${BEAM_VLCKIT_ASSET_BASE_URL:-https://github.com/PrimeCodeSolution/BeamTV/releases/download/$tag}
python3 "$script_dir/package_candidate.py" \
  --staging "$staging" \
  --vlckit "$beam_vlckit_source_dir" \
  --tool-dir "$script_dir" \
  --pins "$beam_pins_file" \
  --asset-base "$asset_base" \
  --platforms "$beam_vlckit_platforms"

(
  cd "$staging"
  find . -type f ! -name SHA256SUMS ! -name VERIFIED -print0 \
    | LC_ALL=C sort -z \
    | xargs -0 shasum -a 256
) > "$staging/SHA256SUMS"

echo "Packaged $beam_vlckit_platforms VLCKit release candidate beneath $staging/artifacts."
