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

# Prerequisites
for debfile in control.vendor-cuda rules.vendor-cuda; do
    if ! [ -f "debian/${debfile}" ]; then
        echo "debian/${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"

debian_version="$(dpkg-parsechangelog -SVersion)"
revision="$(echo "$debian_version" | sed -r 's/.*-//')"
revision_n="${revision%%[!0-9]*}"
vhead="${debian_version%-"$revision"}"
debian_version_plus1="$vhead-$((revision_n+1))"


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 ..."

if [ -f debian/control.vendor-cuda ]; then
    mv debian/control debian/control.orig
    mv debian/control.vendor-cuda debian/control
	sed -i -e "s/@GGML_DEBIAN_VERSION@/$debian_version/" debian/control
	sed -i -e "s/@GGML_DEBIAN_VERSION_PLUS1@/$debian_version_plus1/" debian/control
fi

if [ -f debian/rules.vendor-cuda ]; then
    mv debian/rules debian/rules.orig
    mv debian/rules.vendor-cuda debian/rules
fi

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

if [ -f debian/tests/control.vendor-cuda ]; then
    mv debian/tests/control debian/tests/control.orig
    mv debian/tests/control.vendor-cuda debian/tests/control
fi

echo "4. Switching debian/not-installed to the vendor CUDA version ..."
if [ -f debian/not-installed.vendor-cuda ]; then
    mv debian/not-installed.vendor-cuda debian/not-installed
fi

echo "5. Switching debian/shlibs.local to the vendor CUDA version ..."
if [ -f debian/shlibs.local.vendor-cuda ]; then
    mv debian/shlibs.local.vendor-cuda debian/shlibs.local
fi

echo "Conversion finished."
