#!/bin/sh
# Cross-compile xz.exe for native Windows (x86_64-w64-mingw32) from the official
# unmodified XZ Utils release tarball.
#
#   build-xz.sh <version> <install_prefix>
#
# The source is NOT patched: we extract the tarball as published and run its own
# configure/make. Only the host (cross-compile target) is overridden.
set -eu

VERSION="$1"
PREFIX="$2"

URL="https://github.com/tukaani-project/xz/releases/download/v${VERSION}/xz-${VERSION}.tar.gz"

echo ">>> building xz ${VERSION} -> ${PREFIX}"

WORK="$(mktemp -d)"
cd "$WORK"

curl -fsSL -o src.tar.gz "$URL"
tar -xzf src.tar.gz
cd "xz-${VERSION}"

# Cross-compile for native Windows. Disable everything not needed to exercise
# the CLI argv path: no shared lib, no nls, static binaries so Wine can run the
# .exe with no extra DLL search.
./configure \
    --host=x86_64-w64-mingw32 \
    --prefix="$PREFIX" \
    --disable-shared \
    --enable-static \
    --disable-nls \
    --disable-doc

make -j"$(nproc)"
make install

cd /
rm -rf "$WORK"

# Sanity: the produced xz must be a PE32+ Windows executable.
file "${PREFIX}/bin/xz.exe" || true
echo ">>> done xz ${VERSION}"
