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

if ! command -v ffprobe >/dev/null 2>&1; then
  echo "ffprobe is required" >&2
  exit 1
fi

if ! ffprobe -version | head -n 1 | grep -Eq '^ffprobe version 8([. ]|$)'; then
  echo "ffprobe 8 is required" >&2
  exit 1
fi

if ! command -v jq >/dev/null 2>&1; then
  echo "jq is required" >&2
  exit 1
fi

script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
crate_dir=$(cd "$script_dir/.." && pwd)
scratch=$(mktemp -d "${TMPDIR:-/tmp}/mp4-track-ffprobe.XXXXXX")
trap 'rm -rf "$scratch"' EXIT

sources=(
  v01_h264_aac_moov_last
  v04_hevc_hvc1_aac
  v06_opus_only
  v05_aac_only
  v03_h264_bframes_ctts_elst
  v01_h264_aac_moov_last
  v14_three_tracks
)

for index in "${!sources[@]}"; do
  source_file="$crate_dir/tests/fixtures/${sources[$index]}.mp4"
  output_file="$scratch/roundtrip-$index.mp4"
  extra=()
  if [[ $index -eq 5 ]]; then
    extra=(co64)
  fi
  cargo run --quiet --manifest-path "$crate_dir/Cargo.toml" --example remux -- \
    "$source_file" "$output_file" "${extra[@]}"
  ffprobe -v error -count_packets -show_streams -of json "$source_file" \
    | jq -c '[.streams[].nb_read_packets]' > "$scratch/source-$index.json"
  ffprobe -v error -count_packets -show_streams -of json "$output_file" \
    | jq -c '[.streams[].nb_read_packets]' > "$scratch/output-$index.json"
  diff -u "$scratch/source-$index.json" "$scratch/output-$index.json"
done
