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

# Prerequisites
NEEDED_FILES="\
control
libggml0-backend-vendor-hip-7.14.install
libggml0-backend-vendor-hip-7.14.links
not-installed
rules
tests/control"
for debfile in $NEEDED_FILES; do
    if ! [ -f "debian/alt-builds/vendor-rocm/${debfile}" ]; then
        echo "debian/alt-builds/vendor-rocm/${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"

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 ..."
mv debian/control debian/control.orig
mv debian/alt-builds/vendor-rocm/control debian/control
sed -i -e "s/@GGML_DEBIAN_VERSION@/$(dpkg-parsechangelog -SVersion)/" debian/control
mv debian/rules debian/rules.orig
mv debian/alt-builds/vendor-rocm/rules debian/rules

echo "3. Switching debian/tests/control to the vendor ROCm version ..."
mv debian/tests/control debian/tests/control.orig
mv debian/alt-builds/vendor-rocm/tests/control debian/tests/control

echo "4. Switching debian/not-installed to the vendor ROCm version ..."
mv debian/alt-builds/vendor-rocm/not-installed debian/not-installed

echo "5. Moving *.install and *.link file(s) for the vendor ROCm version ..."
mv debian/alt-builds/vendor-rocm/*.install debian/
mv debian/alt-builds/vendor-rocm/*.links debian/

echo "6. Removing irrelevant files from the original src:ggml ..."
rm -rf debian/libggml0-backend-blas.* \
    debian/libggml0-backend-hip.* \
    debian/libggml0-backend-rpc.* \
    debian/libggml0-backend-vulkan.* \
    debian/libggml0.* \
    debian/libggml-dev.* \
    debian/switch-* \
	debian/*.orig \
	debian/alt-builds

echo "Conversion finished."
