#!/bin/bash

# The procedure of repacking debs is described here:
# https://unix.stackexchange.com/questions/669004/zst-compression-not-supported-by-apt-dpkg

function Usage {
	echo "$(basename $0) <path/to/pool>"
	exit 1
}

if [ -z "$1" ]; then
	Usage
fi

# We need an absolute path, since we are changing directories later.
# This is a restriction of ar < 3.34
# https://stackoverflow.com/questions/39109435/how-to-ar-x-filename-a-to-different-directory
repo="$(readlink -f "$1")"
if ! [ -d "$repo" ]; then
	echo "$repo is not a directory"
	Usage
fi

while read deb; do
	# Could be empty if there are no debs at all
	if [ -n "$deb" ]; then
	# This whole block could be run in parallel.
	{
		# We'll fetch all .zsts there are...
		if zsts="$(ar t "$deb" | grep -oE '(control|data).tar.zst')"; then
			echo "correcting $deb"
			tmpdir=$(mktemp -d /tmp/repack-debs-XXXXX)
			repacked_deb="${deb%.deb}_repacked.deb"
			cd "$tmpdir"

			ar x "$deb"

			# ...and convert them to .xzs
			for zst in $zsts; do
				zstd -d < $zst | xz > ${zst%.zst}.xz
				rm $zst
			done

			# Finally we repack everything
			ar -m -c -a sdsd "$repacked_deb" debian-binary {control,data}.tar.*
			# This one fails. Wrong order of contents.
			#ar -m -c -a sdsd "$repacked_deb" *

			# If everything looks okay, we can delete the original deb,
			# otherwise we delete the one we created
			if dpkg-deb --info "$repacked_deb" >/dev/null 2>&1; then
				rm "$deb"
			else
				echo "correcting $deb failed"
				rm "$repacked_deb"
			fi

			rm -r "$tmpdir"
		fi
	}&
	fi
done <<< "$(ls "$repo"/*.deb 2> /dev/null)"
wait
