#!/usr/bin/bash

# SPDX-FileCopyrightText: © 2023 Tenstorrent Inc.
# SPDX-License-Identifier: GPL-2.0-only

set -e

machine_readable_output=0

while getopts m arg; do
    case $arg in
        m) machine_readable_output=1;;
        *) exit 1;
    esac
done
shift $(($OPTIND-1))

if [ $# -ne 0 ]; then
    echo "Additional command-line parameters are not accepted." 1>&2
    exit 1
fi

if ! dkms status &> /dev/null; then
    echo "DKMS not found. Run on a system with DKMS installed." 1>&2
    exit 1
fi

if [ ! -e dkms.conf ]; then
    echo "dkms.conf not found. Run from the ttkmd directory." 1>&2
    exit 1
fi

if [ $machine_readable_output -eq 1 ]; then
    exec 3>&1 >/dev/null
fi

package_version=$(sed -nE "s/^[[:space:]]*PACKAGE_VERSION[[:space:]]*=[[:space:]]*\"([^\"]+)\"/\\1/p" dkms.conf)

sudo dkms remove tenstorrent/$package_version --all &> /dev/null || true

temp_dir=$(mktemp -d)
trap 'rm -rf "$temp_dir"' EXIT

tar -X tools/exclude-from-release -cf - . |tar -C "$temp_dir" -xf -

archive="ttkmd_$package_version.tar"

sudo dkms add "$temp_dir"
dkms mktarball tenstorrent/$package_version --archive "$PWD/$archive" --source-only
sudo dkms remove tenstorrent/$package_version --all

if tar -tf "$archive" |grep -q "\\.o$"; then
    rm "$archive"

    echo "ERROR: Archive contains built objects." 1>&2
    echo "This happens when the source tree or dkms-managed copy in /usr/src/tenstorrent-* is unclean." 1>&2
    echo "Remove all tenstorrent modules from dkms, remove /usr/src/tenstorrent-* and try again." 1>&2
    echo "No source archive has been created." 1>&2

    exit 1
fi

echo "DKMS source release in $archive"

if [ $machine_readable_output -eq 1 ]; then
    echo $archive >&3
fi
