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

script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
if [[ $# -ne 1 ]]; then
  echo "usage: $0 <ios|ios,tvos>" >&2
  exit 64
fi
case "$1" in
  ios)
    export BEAM_VLCKIT_PLATFORMS=ios
    export BEAM_VLCKIT_OUTPUT_BASENAME=output-ios
    ;;
  ios,tvos)
    export BEAM_VLCKIT_PLATFORMS=ios,tvos
    export BEAM_VLCKIT_OUTPUT_BASENAME=output-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
lock_dir="$beam_vlckit_work_dir/build.lock"
beam_local_lock_owned=0
cleanup_lock() {
  if [[ $beam_local_lock_owned == 1 ]]; then
    rmdir "$lock_dir" 2>/dev/null || true
  fi
  beam_release_canonical_lock
}
trap cleanup_lock EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
beam_acquire_canonical_lock
if ! mkdir "$lock_dir" 2>/dev/null; then
  beam_die "another Apple VLCKit candidate build owns $lock_dir"
fi
beam_local_lock_owned=1

"$script_dir/prepare_sources.sh"
"$script_dir/preflight.sh" "$beam_vlckit_platforms"

rm -rf "$beam_vlckit_staging_dir"
mkdir -p "$beam_vlckit_staging_dir/logs"
cp "$beam_vlckit_source_metadata" \
  "$beam_vlckit_staging_dir/SOURCE-MANIFEST.txt"

# All selected Apple variants share one VLC source/contrib cache and therefore
# build sequentially. The iOS-only mode never evaluates tvOS pins or Xcode
# destinations.
"$script_dir/build_platform.sh" ios
if beam_platform_selected tvos; then
  "$script_dir/build_platform.sh" tvos
fi

python3 "$script_dir/audit_source_inputs.py" \
  --vlc-root "$beam_vlckit_source_dir/libvlc/vlc" \
  --output "$beam_vlckit_staging_dir/audit/source-inputs-sha512.tsv"

"$script_dir/package_candidate.sh" \
  "$beam_vlckit_staging_dir" "$beam_vlckit_platforms"
"$script_dir/verify_candidate.sh" "$beam_vlckit_staging_dir"

previous="$beam_vlckit_work_dir/$beam_vlckit_output_basename.previous"
rm -rf "$previous"
if [[ -e "$beam_vlckit_output_dir" ]]; then
  mv "$beam_vlckit_output_dir" "$previous"
fi
mv "$beam_vlckit_staging_dir" "$beam_vlckit_output_dir"
rm -rf "$previous"

echo "Verified $beam_vlckit_platforms VLCKit candidate: $beam_vlckit_output_dir"
