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

# Prerequisites
for debfile in control.vendor-rocm rules.vendor-rocm; 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)"
rocmname="$origname-vendor-rocm"

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:$rocmname"

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

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

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

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

if [ -f debian/control.vendor-rocm ]; then
    mv debian/control debian/control.orig
    mv debian/control.vendor-rocm 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-rocm ]; then
    mv debian/rules debian/rules.orig
    mv debian/rules.vendor-rocm debian/rules
fi

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

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

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

echo "Conversion finished."
