#!/bin/bash
# Convert src:<package> to src:<package>-vendor-cuda-13-2
#
# Based on Mo Zhou's solution for pytorch-cuda and tensorpipe-cuda, with minor
# modifications to maintain a fuller changelog.
set -e

# Prerequisites
for debfile in control.vendor-cuda-13-2 rules.vendor-cuda-13-2; 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
fi


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

upstream_version="$(dpkg-parsechangelog -SVersion | sed -nr 's/^([.0-9]+).*/\1/p')"
upstream_prefix=${upstream_version%.*}
upstream_last=${upstream_version##*.}
last_plus1=$((upstream_last + 1))
upstream_version_plus1="$upstream_prefix.$last_plus1"


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

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

mostrecent="$(dpkg-parsechangelog -SVersion)"
head -n1 debian/changelog > debian/changelog.vendor-cuda-13-2
cat >> debian/changelog.vendor-cuda-13-2 <<EOF

  * Rebuild src:$origname as src:$cudaname with CUDA (non-free) enabled
    - Automatically generated by src:$origname :: debian/cudabuild.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-13-2
sed -i -e "s/^$origname/$cudaname/" debian/changelog.vendor-cuda-13-2
mv debian/changelog debian/changelog.orig
mv debian/changelog.vendor-cuda-13-2 debian/changelog

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

if [ -f debian/control.vendor-cuda-13-2 ]; then
    mv debian/control debian/control.orig
    mv debian/control.vendor-cuda-13-2 debian/control
	sed -i -e "s/@UPSTREAM_VERSION@/$upstream_version/" debian/control
	sed -i -e "s/@UPSTREAM_VERSION_PLUS1@/$upstream_version_plus1/" debian/control
fi

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

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

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

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

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

echo "Conversion finished."
