#!/bin/bash

set -e

PACKAGE_VERSION=$1
ABI=$2
shift 2
FLAVOURS="$@"

if [[ -z "$PACKAGE_VERSION" || -z "$ABI" || -z "$FLAVOURS" ]]; then
    echo "Usage: $0 <version> <flavour>"
    exit 1
fi

get_conflicts() {
    local this_suffix=$1
    local this_flavour=$2
    local package_format=$3
    local result=""
    for file in debian/dkms-packages.*;
    do
        IFS="." read unused suffix <<< $file
        if [ "$this_suffix" != "$suffix" ]; then
            pkg=$(echo $package_format | sed -e "s/@suffix@/$suffix/g" \
                -e "s/@abi@/$ABI/g" \
                -e "s/@flavour@/$flavour/g")
            result="$result $pkg, "
        fi
    done

    echo $result
}

rm -f debian/control.pkgs
for file in debian/dkms-packages.*;
do
    for flavour in $FLAVOURS;
    do
        IFS="." read unused suffix <<< $file;
        bin_conflicts=$(get_conflicts $suffix $flavour "linux-modules-@suffix@-@abi@-@flavour@")
        meta_conflicts=$(get_conflicts $suffix $flavour "linux-modules-@suffix@-@flavour@")
        cat >>debian/control.pkgs <<EOM

Package: linux-modules-$suffix-@ABI@-$flavour
Architecture: arm64
Build-Profiles: <!stage1>
Section: kernel
Conflicts: $bin_conflicts
Depends: \${misc:Depends}, \${shlibs:Depends}, kmod, linux-image-@ABI@-$flavour | linux-image-unsigned-@ABI@-$flavour
Description: Signed ${suffix^} Orin modules
 Signed ${suffix^} Orin modules for use with the $flavour flavour of the Tegra kernel.

Package: linux-modules-$suffix-$flavour
Architecture: arm64
Build-Profiles: <!stage1>
Section: kernel
Conflicts: $meta_conflicts
Depends: \${misc:Depends}, linux-modules-$suffix-@ABI@-$flavour
Description: Signed ${suffix^} Orin modules meta package
 Signed ${suffix^} Orin modules for use with the $flavour flavour of the Tegra kernel.

Package: linux-$flavour-$suffix
Architecture: arm64
Build-Profiles: <!stage1>
Section: kernel
Depends: \${misc:Depends}, linux-$flavour, linux-modules-$suffix-$flavour
Description: ${suffix^} Orin signed modules and kernel meta package
 Meta package to install the $flavour kernel and signed ${suffix^} drivers.
EOM
    done
done