#!/usr/bin/env bash
export GPG_TTY=$(tty)
SIGNKEY=C29E85A199EB347BEACCD6AC0815124B1083C56D

# Function to build repository
build_repo() {
    local SUITE=$1
    local REPO=dists/$SUITE
    local ARCHS="amd64 arm64"
    
    echo "Building $SUITE repository..."
    
    # Build Packages files for each architecture
    for ARCH in $ARCHS; do
        echo "  Building packages for $ARCH..."
        
        # Use dpkg-scanpackages which properly handles architecture filtering
        # Scans both pool/$SUITE and pool/common so dual-compatible packages
        # (shell scripts, statically linked binaries) can live in one place.
        if command -v dpkg-scanpackages >/dev/null 2>&1; then
            # dpkg-scanpackages automatically includes 'all' packages for any architecture
            {
                dpkg-scanpackages -a $ARCH pool/$SUITE 2>/dev/null
                [ -d pool/common ] && dpkg-scanpackages -a $ARCH pool/common 2>/dev/null
            } > $REPO/main/binary-$ARCH/Packages
        else
            # Fallback to apt-ftparchive with filtering
            { apt-ftparchive packages pool/$SUITE; \
              [ -d pool/common ] && apt-ftparchive packages pool/common; } | \
            awk -v target_arch="$ARCH" '
            BEGIN { 
                RS = ""  # Record separator is empty line (paragraph mode)
                ORS = "\n\n"  # Output record separator
            }
            {
                # Check if this package entry contains the target architecture or "all"
                if ($0 ~ "Architecture: " target_arch "($|\n)" || $0 ~ "Architecture: all($|\n)") {
                    print $0
                }
            }' > $REPO/main/binary-$ARCH/Packages
        fi
        
        gzip -fk $REPO/main/binary-$ARCH/Packages
    done
    
    # Build Release file
    apt-ftparchive -c=apt-release-$SUITE.conf release $REPO > $REPO/Release
    
    # Sign Release files
    gpg --default-key $SIGNKEY --clearsign -o $REPO/InRelease.new $REPO/Release \
      && mv $REPO/InRelease.new $REPO/InRelease
    gpg --default-key $SIGNKEY -abs -o $REPO/Release.gpg.new $REPO/Release \
      && mv $REPO/Release.gpg.new $REPO/Release.gpg
    
    echo "Completed $SUITE repository"
}

# Build both repositories
build_repo bookworm
build_repo trixie
