#!/usr/bin/env bash
# Lumen libmpv-2.dll for Windows x64 (D193) — run inside the `lumen-build`
# WSL distro (Ubuntu 24.04, provisioned per tools/libmpv/README.md):
#
#   wsl -d lumen-build -u root -- bash /mnt/d/BIONICS/Strello/tools/libmpv/build-libmpv.sh
#
# Upstream shinchiro/mpv-winbuild-cmake (maintained, green) patched by
# lgpl_full.py: LGPL posture, full decoder set, mpv + FFmpeg pinned to
# release tags. Builds the gcc cross toolchain first (once), then every
# dependency, FFmpeg, and mpv; packages `mpv-dev-*.7z` with libmpv-2.dll.
# ~4-5 h on 4 cores, ~15 GB. The build tree lives on the distro's ext4
# (fast); only the result is copied out.
set -euo pipefail

ROOT=${ROOT:-/root/libmpv}
UPSTREAM=${UPSTREAM:-https://github.com/shinchiro/mpv-winbuild-cmake.git}
UPSTREAM_REF=${UPSTREAM_REF:-master}
MPV_TAG=${MPV_TAG:-v0.41.0}
FFMPEG_TAG=${FFMPEG_TAG:-n9.0.1}
JOBS=${JOBS:-$(nproc)}
OUT=${OUT:-/mnt/d/BIONICS/Strello/tools/libmpv/out}
HERE=$(cd "$(dirname "$0")" && pwd)

mkdir -p "$ROOT" "$OUT"
exec > >(tee -a "$ROOT/build.log") 2>&1
echo "=== $(date -u +%FT%TZ) lumen libmpv build: mpv=$MPV_TAG ffmpeg=$FFMPEG_TAG jobs=$JOBS"

cd "$ROOT"
if [ ! -d recipe/.git ]; then
  git clone --depth 1 -b "$UPSTREAM_REF" "$UPSTREAM" recipe
fi
git -C recipe rev-parse HEAD | tee recipe.commit
python3 "$HERE/lgpl_full.py" "$ROOT/recipe" "$MPV_TAG" "$FFMPEG_TAG"
grep -n "disable-gpl\|GIT_TAG" recipe/packages/ffmpeg.cmake recipe/packages/mpv.cmake

cmake -DTARGET_ARCH=x86_64-w64-mingw32 \
      -DSINGLE_SOURCE_LOCATION="$ROOT/src_packages" \
      -DRUSTUP_LOCATION="$ROOT/install_rustup" \
      -DENABLE_CCACHE=ON -DMAKEJOBS="$JOBS" \
      -G Ninja -B build_x86_64 -S "$ROOT/recipe"

echo "=== $(date -u +%FT%TZ) download"
ninja -C build_x86_64 download || true
if [ ! -f build_x86_64/install/bin/cross-gcc ]; then
  echo "=== $(date -u +%FT%TZ) toolchain (gcc)"
  ninja -C build_x86_64 gcc
fi
# `update` = the recipe's force-update step: `git am --abort`, fetch, and
# reset every git package to its ref (pinned tags stay pinned). Without it
# a resumed build re-applies patches onto already-patched trees and dies
# with "could not build fake ancestor" (luajit, attempt 2). Upstream CI
# runs it before every build for exactly this reason.
echo "=== $(date -u +%FT%TZ) update (reset git packages to their refs)"
ninja -C build_x86_64 update
echo "=== $(date -u +%FT%TZ) mpv + dependencies"
ninja -C build_x86_64 mpv
echo "=== $(date -u +%FT%TZ) packaging"
ninja -C build_x86_64 mpv-packaging
ls -la build_x86_64/mpv-dev-*.7z
cp -f build_x86_64/mpv-dev-*.7z "$OUT/"
cp -f recipe.commit "$OUT/recipe.commit"
echo "mpv=$MPV_TAG ffmpeg=$FFMPEG_TAG recipe=$(cat recipe.commit) built=$(date -u +%FT%TZ)" > "$OUT/BUILD_INFO"
echo "=== $(date -u +%FT%TZ) BUILD_DONE"
