#!/bin/sh
# Download and inject the nightly build number into the orig tarball
#
# Because we already repack the upstream source, we no longer have bit-by-bit
# equivalance to upstream's tarball, so we can inject the file directly.
set -eu

if ! [ "${1:-}" = "--upstream-version" ]; then
    echo "This script is supposed to be invoked by uscan, not directly." >&2
    exit 1
fi

SCRATCHSPACE="$(mktemp -d)"
trap 'rm -rf "$SCRATCHSPACE"' QUIT INT EXIT

UPSTREAM_VERSION="$2"
ORIG_TARBALL="../llama.cpp_${UPSTREAM_VERSION}.orig.tar.xz"
# Strip off all suffixes
UPSTREAM_RELEASE="$(echo "$UPSTREAM_VERSION" | sed -E 's/^([.0-9]+).*/\1/')"

TAGTXT_URL="https://github.com/ggml-org/llama.cpp/releases/download/v$UPSTREAM_RELEASE/nightly-tag.txt"
TAGTXT_OUT="$SCRATCHSPACE/llama.cpp-$UPSTREAM_RELEASE/nightly-tag.txt"

tar --extract --file "$ORIG_TARBALL" --directory "$SCRATCHSPACE"

if [ -x /usr/bin/wget ]; then
    wget -O "$TAGTXT_OUT" "$TAGTXT_URL" >/dev/null
elif [ -x /usr/bin/curl ]; then
    curl -o "$TAGTXT_OUT" "$TAGTXT_URL" >/dev/null
else
    echo "wget or curl must be installed." >&2
    exit 1
fi

tar --create --xz --sort=name --owner=root:0 --group=root:0 --numeric-owner \
    --file "$ORIG_TARBALL" --directory "$SCRATCHSPACE" llama.cpp-"$UPSTREAM_RELEASE"
