#!/bin/sh

# Work out which firmware files to include in the image
# Several steps:
#
# 1. Look for firmware packages just like a regular debian-cd build with
#    non-free enabled would do (see NONFREE_COMPONENTS variable for details)
# 2. Add them into the firmware temp tree
# 3. Make images (tar.gz, zip) of that tree

set -e

export MIRROR=$1
export CODENAME=$2
TMPDIR=$3
export LC_ALL=C

if [ "$MIRROR"x = ""x ] || \
	[ "$CODENAME"x = ""x ] || \
	[ "$TMPDIR"x = ""x ] ; then
	echo "$0: Need parameters"
	exit 1
fi

rm -rf $TMPDIR/firmware
mkdir -p $TMPDIR/firmware

# Debian 12+ official images use main and non-free-firmware, Debian 11
# sticks to the three historical components:
case $CODENAME in
	bullseye)
		export FIRMWARE_COMPONENTS="main contrib non-free"
		GENERATE_DEP11=0
		;;
	*)
		export FIRMWARE_COMPONENTS="main non-free-firmware"
		GENERATE_DEP11=1
		;;
esac

# Initialize metadata directory:
if [ $GENERATE_DEP11 = 1 ]; then
	FW_DEP11_DIR=$TMPDIR/firmware/dep11
	mkdir $FW_DEP11_DIR
	echo "These files help Debian Installer detect helpful firmware packages (via hw-detect)." > $FW_DEP11_DIR/README.txt
fi

# This tool requires environment variables (exported earlier) and two parameters; the second one has
# a special value for us to use. Deduplication should happen there, but uniquify to make sure:
$BASEDIR/tools/generate_firmware_task '*' --list-filenames-and-indices | sort -u | while read FILE INDICES; do
	cp ${MIRROR}/$FILE $TMPDIR/firmware

	# Adding metadata for bullseye might be helpful but disruptive, be careful:
	[ $GENERATE_DEP11 = 0 ] && continue

	# Beware of variable interpolation when using the INDICES variable, it
	# contains 'binary-*'!
	COMPONENT=$(echo "$INDICES"|sed 's,/binary-.*,,'|xargs basename)
	DEP11_DIR=$(echo "$INDICES"|sed 's,/binary-.*,,')/dep11
	PACKAGE=$(dpkg -f $MIRROR/$FILE Package)

	# Mimic make_disc_trees.pl, except it only passes a single Components-<arch>.yml.gz while
	# we pass all of them. Differences are unlikely though, as interesting firmware packages
	# are "Architecture: all".
	$BASEDIR/tools/generate_firmware_patterns \
		-v --output-dir $FW_DEP11_DIR \
		--package $PACKAGE $DEP11_DIR/Components-*.yml.gz
	if [ -f $FW_DEP11_DIR/$PACKAGE.patterns ]; then
        	printf "%s\n" $COMPONENT > $FW_DEP11_DIR/$PACKAGE.component
	fi

	# XXX: Keep in line with make_disc_trees.pl!
	BASEFILE=$(basename $FILE)
	dpkg --contents ${MIRROR}/$FILE | \
		perl -ne 'printf "%-55s %s %s\n", "/$1", "'$BASEFILE'", "'$COMPONENT'"
			if m,^[-|l]\S+\s+\S+\s+\d+\s+\S+\s+\S+\s+./(\S+/firmware/\S+),' >> $TMPDIR/firmware/Contents-firmware
done

cd $TMPDIR/firmware
tar czf ../firmware.tar.gz .
zip -9rq ../firmware.zip .
find . -type f | gzip -9 > ../firmware.list.gz
cd ..
find firmware | cpio --quiet -o -H newc | pigz -9nm > firmware.cpio.gz
ls -l $PWD/firmware.cpio.gz $PWD/firmware.tar.gz $PWD/firmware.zip

sha256sum firmware.* > SHA256SUMS
sha512sum firmware.* > SHA512SUMS
