#!/bin/bash
# Convert src:<package> to src:<package>-vendor-cuda
#
# Based on switch-ggml-cuda.sh
set -e

# Prerequisites
NEEDED_FILES="\
control
libggml0-backend-vendor-cuda-13.install
libggml0-backend-vendor-cuda-13.links
not-installed
rules
shlibs.local
tests/control"
for debfile in $NEEDED_FILES; do
    if ! [ -f "debian/alt-builds/vendor-cuda/${debfile}" ]; then
        echo "debian/alt-builds/vendor-cuda/${debfile} not found." >&2
        exit 1
    fi
done
if [ -z "$DEBFULLNAME" ] || [ -z "$DEBEMAIL" ]; then
    echo "DEBFULLNAME and DEBEMAIL envvars must be set." >&2
    exit 1
fi

origname="$(dpkg-parsechangelog -SSource)"
cudaname="$origname-vendor-cuda"

echo "Converting src:$origname to src:$cudaname"

echo "1. Preparing debian/changelog ..."

head -n1 debian/changelog >debian/changelog.vendor-cuda
cat >>debian/changelog.vendor-cuda <<EOF

  * Rebuild src:$origname as src:$cudaname with vendor CUDA enabled
    - Automatically generated by src:$origname :: debian/switch-ggml-vendor-cuda.sh
    - Please observe README.Source when making changes
    - Changelog entries below are from src:$origname
EOF
tail -n +2 debian/changelog >>debian/changelog.vendor-cuda
sed -i -e "s/^$origname/$cudaname/" debian/changelog.vendor-cuda
mv debian/changelog debian/changelog.orig
mv debian/changelog.vendor-cuda debian/changelog

echo "2. Switching debian/{rules,control} to the vendor CUDA version ..."

mv debian/control debian/control.orig
mv debian/alt-builds/vendor-cuda/control debian/control
sed -i -e "s/@GGML_DEBIAN_VERSION@/$(dpkg-parsechangelog -SVersion)/" debian/control
mv debian/rules debian/rules.orig
mv debian/alt-builds/vendor-cuda/rules debian/rules

echo "3. Switching debian/tests/control to the vendor CUDA version ..."

mv debian/tests/control debian/tests/control.orig
mv debian/alt-builds/vendor-cuda/tests/control debian/tests/control

echo "4. Switching debian/not-installed to the vendor CUDA version ..."
mv debian/alt-builds/vendor-cuda/not-installed debian/not-installed

echo "5. Switching debian/shlibs.local to the vendor CUDA version ..."
mv debian/alt-builds/vendor-cuda/shlibs.local debian/shlibs.local

echo "5. Moving *.install and *.link file(s) for the vendor CUDA version ..."
mv debian/alt-builds/vendor-cuda/*.install debian/
mv debian/alt-builds/vendor-cuda/*.links debian/

echo "6. Removing irrelevant files from the original src:ggml ..."
rm -rf debian/libggml0-backend-blas.* \
    debian/libggml0-backend-hip.* \
    debian/libggml0-backend-rpc.* \
    debian/libggml0-backend-vulkan.* \
    debian/libggml0.* \
    debian/libggml-dev.* \
    debian/switch-* \
	debian/*.orig \
	debian/alt-builds

echo "Conversion finished."
