#!/bin/sh
#
# This script is used to create a fake orig tarball that concatenates
# the DKMS packages from a MOFED release source tarball.
#
# It also removes some undesired files that are shipped in that tarball.
# Hopefully in the future upstream starts to clean up the releases so
# we do not have to do it here.
#
# Example usage: ./create-orig.sh ../../MLNX_OFED_SRC-debian-24.04-0.7.0.0.tgz

set -eu

MOFED_TGZ="$1"

tmpdir="$(mktemp -td doca-ofed-create-orig.XXXXXXXXXX)"
echo "Using tmpdir $tmpdir"

echo "Extracting $MOFED_TGZ to $tmpdir"
tar xf "$MOFED_TGZ" -C "$tmpdir"

# Use a loop to store shell glob into var
for dir in "$tmpdir"/MLNX*
do
	MOFED_DIR="$dir"
done

MOFED_DIRNAME=$(basename "$dir")

# Example version: 24.04-0.6.6.0
MOFED_VERSION=${MOFED_DIRNAME##MLNX_OFED_SRC-}
echo "Detected MOFED version $MOFED_VERSION"

# Split minor from major version, and recompose to a Debian-compatible
# full version, eg. 24.04.0.6.6.0
MOFED_VERSION_MAJOR=${MOFED_VERSION%%-*}
echo "Extracted MOFED version major $MOFED_VERSION_MAJOR"

MOFED_VERSION_MINOR=${MOFED_VERSION##*-}
echo "Extracted MOFED version minor $MOFED_VERSION_MINOR"

MOFED_DEBIAN_VERSION="$MOFED_VERSION_MAJOR.$MOFED_VERSION_MINOR"
echo "Recomposed MOFED debian version $MOFED_DEBIAN_VERSION"

MOFED_SRCDIR=$MOFED_DIR/SOURCES

dest="$tmpdir/doca-ofed"
mkdir "$dest"

for pkg in \
	mlnx-ofed-kernel \
	iser \
	isert \
	mlnx-nfsrdma \
	mlnx-nvme \
	srp \
	kernel-mft \
	xpmem
do
	pkgdest="$dest/$pkg"
	echo "Extracting $pkg to $pkgdest"
	mkdir "$pkgdest"
	tar xf "$MOFED_SRCDIR/${pkg}_"*.orig.tar* -C "$pkgdest" --strip-components 1
done

echo "Removing upstream cache files"
rm -vrf "$dest/mlnx-ofed-kernel/compat/autom4te.cache"

echo "Removing upstream temporary files"
rm -vf "$dest/mlnx-nvme/host/.Makefile.swp"
rm -vf "$dest/mlnx-ofed-kernel/drivers/nvme/host/.Makefile.swp"

echo "Removing upstream VCS files"
rm -vf "$dest/mlnx-ofed-kernel/.gitignore"
rm -vf "$dest/mlnx-ofed-kernel/compat/config/.gitignore"
rm -vrf "$dest/xpmem/.github"
rm -vf "$dest/xpmem/.gitignore"

tarfile="doca-ofed_$MOFED_DEBIAN_VERSION.orig.tar.xz"
echo "Creating tar file $tarfile"

tar acf "$tarfile" -C "$tmpdir" "doca-ofed"

echo "Cleanup, removing $tmpdir"

echo "Done"
