#!/bin/sh
#
# Copy firmware into the right directories in preparation for building udebs.
#
# Copyright (c) 2001-2002 Herbert Xu <herbert@debian.org>
# Copyright (c) 2004 Canonical Ltd. Adapted for firmware by Colin Watson.
#
# Usage: copy-firmware version flavour installedname

set -e

processfirmware() {
	local list=$1
	local fwdir=$2
	local fullversion=$3
	
	cp $list $tmpdir/work
	local missing=0
	(
		while read file; do
			if echo "$file" | grep -q -- '^#' || [ -z "$file" ]; then
				continue
			fi

			if echo "$file" | grep -q -- '^-'; then
				optional=1
				file=$(echo $file | sed 's/^-//');
			else
				optional=0
			fi
			if [ -e $fwdir/$file-$fullversion ]; then
				echo $file-$fullversion
			else
				if [ "$optional" = 0 ]; then
					echo "missing firmware $file" >&2
					exit 1
				fi
			fi
		done
	) < $tmpdir/work > $list
}

version=$1-$2
flavour=$2
installedname=$3
arch=$(dpkg-architecture -qDEB_HOST_ARCH)
home=$PWD

trap 'rm -rf $tmpdir' EXIT
tmpdir=$(tempfile)
rm $tmpdir
mkdir $tmpdir

# SOURCEDIR may be set externally to control where to copy from.
if [ -n "$SOURCEDIR" ]; then
	fwdir=$SOURCEDIR/lib/hotplug/firmware
else
	fwdir=/lib/hotplug/firmware
fi

if [ ! -d $fwdir ] || [ ! -d firmware ]; then
	exit 0
fi

# The directory of firmware lists to use.
if [ -d firmware/$arch-$flavour ]; then
	fwlistdir=firmware/$arch-$flavour
elif [ -d firmware/$flavour ]; then
	fwlistdir=firmware/$flavour
else
	fwlistdir=firmware/$arch
fi

mkdir $tmpdir/firmware-list

# loop over all udebs
for i in $(
	find $fwlistdir -maxdepth 1 \( -type f -or -type l \) -not -name '*.lnk' -printf "%f\t%f\n"
); do
	# Sort so that the joins work, no matter what the order of the
	# input file.
	sort $home/$fwlistdir/$i > $tmpdir/firmware-list/$i

	# deal with firmware marked as optional and other transformations
	processfirmware $tmpdir/firmware-list/$i $fwdir $installedname

	if [ -s $tmpdir/firmware-list/$i ] && dh_listpackages | grep -qx "$i-$version-di"; then
		# copy firmware to package build dir
		cd $fwdir
		ret=$( ( (
			set +e
			tar cfT - $tmpdir/firmware-list/$i
			printf $? >&3
		) | (
			set +e
			dir=$home/debian/$i-$version-di/lib/hotplug/firmware
			mkdir -p $dir
			cd $dir
			tar xf -
			printf $? >&3
		) ) 3>&1)
		if [ "$ret" != "00" ]; then
			echo "tar failed" >&2
			exit $ret
		fi
		cd $home
	fi
done
