#!/bin/bash

ARCH_DIR="amd64"
ARCH="amd64"
PACKAGES_FILE="Packages"

while true; do
    OUTPUT=$(dpkg-scanpackages --arch "$ARCH" "$ARCH_DIR/" 2>&1)
    
    echo "$OUTPUT" | tee /tmp/dpkg_scan_output.log

    # Check for the specific error
    BAD_FILE=$(echo "$OUTPUT" | grep "uses unknown compression for member 'control.tar.zst'" | sed -n "s/.*archive '\(.*\.deb\)'.*/\1/p")

    if [ -n "$BAD_FILE" ]; then
        echo "Removing problematic file: $BAD_FILE"
        rm -f "$BAD_FILE"
        echo "Retrying dpkg-scanpackages..."
    else
        # If no error, write output to Packages file and break loop
        dpkg-scanpackages --arch "$ARCH" "$ARCH_DIR/" > "$PACKAGES_FILE"
        echo "Packages file generated successfully."
        break
    fi
done

