#!/bin/bash
# Convert src:<package> to src:<package>-cuda
#
# 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.cuda rules.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
fi



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

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

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

mostrecent="$(dpkg-parsechangelog -SVersion)"
head -n1 debian/changelog > debian/changelog.cuda
cat >> debian/changelog.cuda <<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.cuda
sed -i -e "s/^$origname/$cudaname/" debian/changelog.cuda
mv debian/changelog debian/changelog.orig
mv debian/changelog.cuda debian/changelog

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

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

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

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

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

echo "Convertion finished."
