#!/bin/bash
# Batch process all crates in debian/missing-sources/
# Generate debian/copyright.in.d/ fragments

set -e

VENDOR_DIR="debian/missing-sources"
FRAGMENTS_DIR="debian/copyright.in.d"
BIN_DIR="debian/bin"

mkdir -p "$FRAGMENTS_DIR"

# Count crates by file count (smallest first)
echo "Analyzing crates..."
crate_list=$(mktemp)
for crate_dir in "$VENDOR_DIR"/*/ ; do
    crate_dir="${crate_dir%/}"
    file_count=$(find "$crate_dir" -type f | wc -l)
    echo "$file_count|$crate_dir" >> "$crate_list"
done

# Sort by file count (smallest first)
sort -n -t'|' -k1 "$crate_list" -o "$crate_list"

# Count totals
total_crates=$(wc -l < "$crate_list")
processed=0
stubs=0
skipped=0
errors=0

echo "Processing $total_crates crates from $VENDOR_DIR..."
echo

# Process each crate
while IFS='|' read -r file_count crate_dir; do
    crate=$(basename "$crate_dir")
    fragment="$FRAGMENTS_DIR/$crate"
    current=$((processed+stubs+skipped+errors+1))
    
    # Skip if already exists and is valid
    if [ -f "$fragment" ]; then
        # Check if it's an empty file (stub)
        if [ ! -s "$fragment" ]; then
            # Empty fragment - verify it's actually a stub
            if "$BIN_DIR/is-stub.sh" "$crate_dir" 2>/dev/null; then
                echo "  [$current/$total_crates] $crate: already done (stub)"
                ((stubs++))
                continue
            fi
        else
            # Non-empty fragment exists - assume it's done
            echo "  [$current/$total_crates] $crate: already done"
            ((skipped++))
            continue
        fi
    fi
    
    # Process the crate
    if "$BIN_DIR/process-crate.sh" "$crate_dir" 2>&1; then
        if [ ! -s "$fragment" ]; then
            ((stubs++))
        else
            ((processed++))
        fi
    else
        echo "  [$current/$total_crates] $crate: ERROR - failed to process"
        ((errors++))
    fi
done < "$crate_list"

rm "$crate_list"

echo
echo "Summary:"
echo "  Total crates: $total_crates"
echo "  Already done: $skipped"
echo "  Stubs: $stubs"
echo "  Successfully processed: $processed"
echo "  Errors: $errors"

if [ $errors -eq 0 ] && [ $((processed+stubs+skipped)) -eq $total_crates ]; then
    echo
    echo "All crates processed successfully!"
    echo "Run: debian/bin/merge-copyright"
fi
