#!/bin/sh
#
# Fetch list of packages with firmware to store in the data package,
# while we wait for DEP-11 to gain support for it and a lightweight
# method to look it up.

set -e

mirror=http://deb.debian.org/debian

mkdir -p generated

for dist in jessie stretch sid; do
    echo "fetching Release file for $dist"
    archs="$(curl --silent --location $mirror/dists/$dist/Release | awk -F: '/^Architectures/ {print $2}')"
    for arch in $archs; do
	for section in "main" "contrib" "non-free"; do
            # "" is main in Wheezy.
	    if [  main = "$section" ] && [ wheezy = "$dist" ]; then
		url="$mirror/dists/$dist/Contents-$arch.gz"
	    else
		url="$mirror/dists/$dist/$section/Contents-$arch.gz"
	    fi
	    echo "fetching $url"
            fwfile="generated/Fw-Contents-$arch-$dist-$section"
	    if curl --silent --location "$url" > "$fwfile-full.gz" ; then
		if gunzip 2>/dev/null < $fwfile-full.gz | grep ^lib/firmware > "$fwfile" ; then
		    :
		else
                    echo "warning: unable to find any firmware for $arch in $dist section $section"
		fi
	    else
		echo "error: unable to download any info for $arch in $dist section $section"
	    fi
	    rm "$fwfile-full.gz"
            if [ -e "$fwfile" ] && [ ! -s "$fwfile" ]; then
                echo "warning: empty firmware file for $arch in $dist section $section removed"
                rm "$fwfile"
            fi
	done
	sleep 1
    done
done
