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

script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=common.sh
source "$script_dir/common.sh"

beam_assert_work_dir
lock_dir="$beam_vlckit_work_dir/prepare.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
export LC_ALL=C
profile=${BEAM_VLCKIT_MESON_PROFILE:-$BEAM_MESON_PROFILE}
case "$profile" in
  stable|meson-1.9) ;;
  *) beam_die "BEAM_VLCKIT_MESON_PROFILE must be stable or meson-1.9" ;;
esac

BEAM_PREFLIGHT_ALLOW_UNPREPARED=1 \
  "$script_dir/preflight.sh" "$beam_vlckit_platforms"

if ! mkdir "$lock_dir" 2>/dev/null; then
  beam_die "another Apple VLCKit source preparation/build owns $lock_dir"
fi
beam_local_lock_owned=1

staging="$beam_vlckit_build_root/source.staging"
source_parent="$beam_vlckit_source_parent"
previous="$beam_vlckit_build_root/source.previous"
rm -rf "$staging" "$previous"
mkdir -p "$staging"

clone_exact() {
  local repository=$1
  local revision=$2
  local destination=$3
  git init -q "$destination"
  git -C "$destination" remote add origin "$repository"
  git -C "$destination" fetch -q --depth 1 origin "$revision"
  git -C "$destination" checkout -q --detach FETCH_HEAD
  [[ "$(git -C "$destination" rev-parse HEAD)" == "$revision" ]] || \
    beam_die "checkout verification failed for $destination"
}

vlckit="$staging/VLCKit"
clone_exact "$BEAM_VLCKIT_REPOSITORY" "$BEAM_VLCKIT_REVISION" "$vlckit"
git -C "$vlckit" apply --check "$script_dir/patches/0001-beam-reproducible-lgpl-build.patch"
git -C "$vlckit" apply "$script_dir/patches/0001-beam-reproducible-lgpl-build.patch"

upstream_patches=("$vlckit"/libvlc/patches/*.patch)
[[ ${#upstream_patches[@]} -eq $BEAM_VLC_UPSTREAM_PATCH_COUNT ]] || \
  beam_die "expected $BEAM_VLC_UPSTREAM_PATCH_COUNT VLCKit VLC patches; found ${#upstream_patches[@]}"

vlc="$vlckit/libvlc/vlc"
clone_exact "$BEAM_VLC_REPOSITORY" "$BEAM_VLC_REVISION" "$vlc"
git -C "$vlc" config user.name 'BEAM reproducible build'
git -C "$vlc" config user.email 'builds@beamtv.app'
export GIT_COMMITTER_NAME='BEAM reproducible build'
export GIT_COMMITTER_EMAIL='builds@beamtv.app'
export GIT_COMMITTER_DATE="@$BEAM_SOURCE_DATE_EPOCH +0000"
export SOURCE_DATE_EPOCH=$BEAM_SOURCE_DATE_EPOCH

git -C "$vlc" am --keep-cr "${upstream_patches[@]}"
upstream_tree=$(git -C "$vlc" rev-parse HEAD^{tree})
[[ "$upstream_tree" == "$BEAM_VLC_UPSTREAM_PATCHED_TREE" ]] || \
  beam_die "the upstream VLCKit patch series produced tree $upstream_tree, expected $BEAM_VLC_UPSTREAM_PATCHED_TREE"

expected_tree=$BEAM_VLC_PATCHED_TREE_STABLE
if [[ "$profile" == meson-1.9 ]]; then
  git -C "$vlc" am --keep-cr "$script_dir/patches/0048-tools-update-meson-to-1.9.0.patch"
  expected_tree=$BEAM_VLC_PATCHED_TREE_MESON_1_9
fi
actual_tree=$(git -C "$vlc" rev-parse HEAD^{tree})
[[ "$actual_tree" == "$expected_tree" ]] || \
  beam_die "prepared VLC tree $actual_tree does not match pinned $expected_tree"

meson_version=$(awk -F= '$1 == "MESON_VERSION" {print $2}' "$vlc/extras/tools/packages.mak")
meson_sum=$(awk -v file="meson-$meson_version.tar.gz" '$2 == file {print $1}' "$vlc/extras/tools/SHA512SUMS")
if [[ "$profile" == stable ]]; then
  [[ "$meson_version" == "$BEAM_MESON_STABLE_VERSION" ]] || beam_die "stable Meson version drift"
  [[ "$meson_sum" == "$BEAM_MESON_STABLE_SHA512" ]] || beam_die "stable Meson checksum drift"
else
  [[ "$meson_version" == "$BEAM_MESON_BACKPORT_VERSION" ]] || beam_die "backport Meson version drift"
  [[ "$meson_sum" == "$BEAM_MESON_BACKPORT_SHA512" ]] || beam_die "backport Meson checksum drift"
fi

mkdir -p "$staging/metadata"
{
  printf 'vlckit_revision=%s\n' "$BEAM_VLCKIT_REVISION"
  printf 'vlc_revision=%s\n' "$BEAM_VLC_REVISION"
  printf 'vlc_upstream_patched_tree=%s\n' "$upstream_tree"
  printf 'vlc_final_tree=%s\n' "$actual_tree"
  printf 'meson_profile=%s\n' "$profile"
  printf 'meson_version=%s\n' "$meson_version"
  printf 'source_date_epoch=%s\n' "$BEAM_SOURCE_DATE_EPOCH"
  printf 'vlckit_build_patch_sha256=%s\n' \
    "$(beam_sha256 "$script_dir/patches/0001-beam-reproducible-lgpl-build.patch")"
  printf 'meson_backport_patch_sha256=%s\n' \
    "$(beam_sha256 "$script_dir/patches/0048-tools-update-meson-to-1.9.0.patch")"
} > "$staging/metadata/SOURCE-MANIFEST.txt"

if [[ -e "$source_parent" ]]; then
  mv "$source_parent" "$previous"
fi
mv "$staging" "$source_parent"
rm -rf "$previous"

echo "Prepared pinned Apple VLCKit sources at $beam_vlckit_source_dir ($profile)."
