#!/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 persistent changelog.cuda.
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 "1. preparing debian/changelog ..."

ORIGVER="$(dpkg-parsechangelog -SVersion)"
CUDAVER="$(dpkg-parsechangelog -SVersion -ldebian/changelog.cuda 2>/dev/null || true)"
if [ "$ORIGVER" != "$CUDAVER" ]; then
    head -n1 debian/changelog | sed -e "s/^$ORIGNAME/$CUDANAME/" > debian/changelog.cuda.tmp
    cat >> debian/changelog.cuda.tmp <<EOF

  * Rebuild src:$ORIGNAME 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

$(dpkg-parsechangelog -S 'Changes' | tail -n +4)

 -- $DEBFULLNAME <$DEBEMAIL>  $(date -R)
EOF
fi
if ! [ -f debian/changelog.cuda ]; then
    # No entries yet, can use the tmp as-is
    mv debian/changelog.cuda.tmp debian/changelog.cuda
else
    # Prepend the new changelog entry
    if [ "$ORIGVER" != "$CUDAVER" ]; then
        echo "" >> debian/changelog.cuda.tmp
        cat debian/changelog.cuda  >> debian/changelog.cuda.tmp
        mv -f debian/changelog.cuda.tmp debian/changelog.cuda
    fi
fi

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

if ! [ -h debian/changelog ]; then
    mv debian/changelog debian/changelog.orig
    ln -s changelog.cuda debian/changelog
fi

if ! [ -h debian/control ]; then
    mv debian/control debian/control.orig
    ln -s control.cuda debian/control
fi

if ! [ -h debian/rules ]; then
    mv debian/rules debian/rules.orig
    ln -s rules.cuda debian/rules
fi

echo "3. Maintainer notes are shown below"
cat <<EOF
--------------------------------------------------------------------------
You can revert the changes using git checkout
--------------------------------------------------------------------------
Copy the source tarball of src:$ORIGNAME to src:$CUDANAME if sbuild cannot
find it. PLS use the identical source.
--------------------------------------------------------------------------
EOF
