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

script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
if [[ $# -ne 1 ]]; then
  echo "usage: $0 <candidate-dir>" >&2
  exit 64
fi
candidate=$1
manifest="$candidate/BUILD-MANIFEST.txt"
[[ -f "$manifest" && ! -L "$manifest" ]] || {
  echo "candidate BUILD-MANIFEST.txt is missing" >&2
  exit 1
}
platforms=$(awk -F= '
  $1 == "platforms" { count += 1; value = $2 }
  END { if (count != 1) exit 1; print value }
' "$manifest") || {
  echo "candidate manifest must contain exactly one platforms value" >&2
  exit 1
}
case "$platforms" in
  ios|ios,tvos) ;;
  *)
    echo "candidate platforms must be exactly ios or ios,tvos" >&2
    exit 1
    ;;
esac
export BEAM_VLCKIT_PLATFORMS=$platforms
# shellcheck source=common.sh
source "$script_dir/common.sh"

# Validate the package topology and checksums before passing any candidate path
# into binary inspection tools.
python3 "$script_dir/verify_candidate.py" "$candidate"

if beam_platform_selected ios; then
  python3 "$script_dir/audit_xcframework.py" \
    --xcframework "$candidate/frameworks/MobileVLCKit.xcframework" \
    --product MobileVLCKit \
    --platform ios \
    --minimum-os "$BEAM_IOS_DEPLOYMENT_TARGET" \
    --approved-inventory "$candidate/audit/modules/ios/iPhone/approved-module-entries.tsv" \
    --forbidden-prefix "$beam_mobile_dir" \
    --report "$candidate/audit/ios-xcframework.json"
fi
if beam_platform_selected tvos; then
  python3 "$script_dir/audit_xcframework.py" \
    --xcframework "$candidate/frameworks/TVVLCKit.xcframework" \
    --product TVVLCKit \
    --platform tvos \
    --minimum-os "$BEAM_TVOS_DEPLOYMENT_TARGET" \
    --approved-inventory "$candidate/audit/modules/tvos/AppleTV/approved-module-entries.tsv" \
    --forbidden-prefix "$beam_mobile_dir" \
    --report "$candidate/audit/tvos-xcframework.json"
fi

# The audits rewrite deterministic JSON; require it to remain covered by the
# manifest generated during packaging.
python3 "$script_dir/verify_candidate.py" "$candidate"
touch "$candidate/VERIFIED"
if beam_platform_selected ios; then
  touch "$candidate/ios/VERIFIED"
fi
if beam_platform_selected tvos; then
  touch "$candidate/tvos/VERIFIED"
fi
python3 "$script_dir/verify_candidate.py" "$candidate"
