#!/bin/sh
#
# Add (non-free) firmware to the debian-installer initrd used by the
# PXE installation, to make sure it work on more hardware out of the
# box.

set -e

add_firmware_to_initrd() {
    initrd=$1

    tmpdir=$(mktemp -d)
    cd $tmpdir

    echo Finding and downloading firmware .debs
    # Find files.  This require non-free to be enabled as APT
    # repository.
    # Skip installer debs, to avoid the b43 installers that conflict
    # with each other.  FIXME review if this is needed after squeeze.
    debnames="$(apt-cache search ^firmware-.* | grep -v installer | cut -d" " -f1)"

    # Allow caller to ask for extra debs using environment variable
    debnames="$debnames $FIRMWAREDEBNAMES"

    apt-get --download-only -y -q install $debnames

    # Find firmware .deb files
    for name in $debnames ; do
	for deb in /var/cache/apt/archives/${name}_* ; do
	    if [ -f $deb ] ; then
		debs="$debs $deb"
	    fi
	done
    done

    echo Unpacking current initrd
    gunzip < $initrd | cpio --quiet -id

    echo Unpacking firmware files, overwriting any in the original initrd
    for deb in $debs ; do
	if ar p $deb data.tar.gz | tar zxf - ./lib/firmware/ >/dev/null 2>&1 ; then
            :
        else
            echo "Ignoring $deb without /lib/firmware/"
        fi
    done

    timestamp=$(date +%Y%m%dT%H:%M)
    echo Wrapping up new initrd
    find . | cpio --quiet -o -H newc | gzip -9 > $initrd.new &&
        mv $initrd $initrd.old-$timestamp &&
        mv $initrd.new $initrd
    cd /
    rm -rf $tmpdir
}

if [ "$1" ] ; then
    diroot="$1"
fi

# Path to where the d-i pxe boot images were unpacked
if [ -z "$diroot" ] ; then
    diroot=/var/lib/tftpboot/debian-installer
fi

for initrd in $diroot/*/initrd.gz ; do
    if [ -e $initrd ] ; then
        add_firmware_to_initrd "$initrd"
    else
        echo "Unable to open $initrd"
    fi
done
