#!/bin/sh
# build the two release variants and post them to the hf bucket as the new latest
# windows vulkan cross via zig, linux cuda blackwell native via nvcc
# never forks anything, runs both builds in foreground, takes no args
set -e

cd "$(dirname "$0")"

# make nvcc reachable to cmake regardless of the parent shell's PATH
PATH="/usr/local/cuda/bin:$PATH"

HF_REPO="${HF_REPO:-Serveurperso/install.sh}"

# the llama.cpp commit count drives the baked LLAMA_BUILD_NUMBER and the bucket version
N=$(git -C deps/llamacpp rev-list --count HEAD)
VERSION="b${N}"
echo "building ${VERSION} for ${HF_REPO}"

# wipe output so the bucket sync mirrors exactly what we produce this run
rm -rf output

# windows vulkan baseline, x86_64 cpu floor, the broadest desktop target
cmake --workflow --preset x86_64-windows-vulkan-kkkkk

# linux cuda blackwell, sm 120, native nvcc, the local rig target
cmake --workflow --preset x86_64-linux-cuda-120

# pull featcode and unzstd, but only for the two pairs we actually build this run
# upstream CI builds the whole matrix so its fetch is unfiltered, ours stays strict
python3 - <<'PY'
import json, pathlib, urllib.request
keep = {("x86_64", "linux"), ("x86_64", "windows")}
for item in json.load(open("artefacts.json")):
    dst = pathlib.Path(item["dst"])
    parts = dst.parts
    if len(parts) >= 4 and (parts[1], parts[2]) in keep:
        dst.parent.mkdir(parents=True, exist_ok=True)
        urllib.request.urlretrieve(item["src"], dst)
        print(f"fetched {dst}")
PY

# decompress the windows binary at the packager root so wine can launch it without ceremony
unzstd -q -f -o llama.exe output/x86_64/windows/vulkan/kkkkk/llama-app.zst

# upload the bN tree, sync_bucket merges into hf://buckets/${HF_REPO}/${VERSION}/
python3 scripts/upload.py "${HF_REPO}/${VERSION}"

# bump latest the upstream way: same output dir, mirror only this one file at the bucket root
rm -rf output
mkdir output
printf '%s' "${VERSION}" > output/latest
python3 scripts/upload.py "${HF_REPO}"
rm -rf output

echo "done: ${VERSION} live on ${HF_REPO}, llama.exe ready for wine"
