# Windows entrypoint for the self-built FFmpeg binary (win/x64).
#
# FFmpeg/x264/lame use GNU autotools + make, which need a Unix-like toolchain. The standard
# Windows path is MSYS2 + MinGW-w64. This script locates the MSYS2 bash and runs the shared
# build-ffmpeg-core.sh recipe under the MinGW64 environment, producing a static ffmpeg.exe.
#
# One-time setup on the build machine:
#   1. Install MSYS2 from https://www.msys2.org
#   2. In the "MSYS2 MinGW64" shell:
#        pacman -S --needed base-devel mingw-w64-x86_64-toolchain mingw-w64-x86_64-nasm make git
#   3. Ensure Node.js is installed and on PATH (already required for this repo).

$ErrorActionPreference = "Stop"
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

# Locate MSYS2 bash.
$candidates = @(
    $env:MSYS2_BASH,
    "C:\msys64\usr\bin\bash.exe"
)
if ($env:MSYS2_ROOT) {
    $candidates += (Join-Path $env:MSYS2_ROOT "usr\bin\bash.exe")
}
$bash = $candidates | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1

if (-not $bash) {
    Write-Error @"
FFmpeg build requires MSYS2/MinGW, which was not found.
Install MSYS2 from https://www.msys2.org, then in the "MSYS2 MinGW64" shell run:
  pacman -S --needed base-devel mingw-w64-x86_64-toolchain mingw-w64-x86_64-nasm make git
Then re-run this build. (Set the MSYS2_BASH env var to bash.exe if MSYS2 is in a custom location.)
"@
    exit 1
}

Write-Host "Using MSYS2 bash: $bash"

# Pass the core script using a forward-slash path that MSYS2 bash understands.
$core = (Join-Path $ScriptDir "build-ffmpeg-core.sh") -replace '\\', '/'

# Run non-login so the Windows PATH (with node) is inherited, but:
#   - MSYSTEM=MINGW64 makes `uname -s` report MINGW64 instead of MSYS, which
#     FFmpeg's configure refuses to build against ("Native MSYS builds are
#     discouraged"). This is what the "MSYS2 MinGW64" shortcut sets internally.
#   - Prepend MinGW64 (gcc/nasm/pkg-config) and MSYS /usr/bin (make/git/tar/
#     curl/env) to PATH. /mingw64/bin must come first so gcc is the mingw-w64
#     toolchain, not the MSYS one.
& $bash -c "export MSYSTEM=MINGW64; export PATH=/mingw64/bin:/usr/bin:`$PATH; bash '$core' win x64"
exit $LASTEXITCODE
