#!/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 code=0
	cp $list $tmpdir/work
	(
		code=0
		while read firmware; do
			# Question mark suffixed firmware files are optional.
			# Support dash prefixing for backwards compatibility.
			if [ "${firmware#-}" != "$firmware" ] || \
			   [ "${firmware% \?}" != "$firmware" ]; then
				optional=1
				firmware=${firmware% \?}
				firmware=${firmware#-}
			else
				optional=0
			fi

			if [ -e $fwdir/$firmware ]; then
				echo $firmware
			else
				if [ "$optional" = 0 ]; then
					echo "missing firmware $firmware" >&2
					if [ -z "$KW_CHECK_NONFATAL" ]; then
						code=1
					fi
				fi
			fi
		done
		exit $code
	) < $tmpdir/work > $list.new || code=$?
	sort < $list.new > $list
	rm -f $list.new
	return $code
}

version=$1-$2
flavour=$2
installedname=$3
configdir=$(readlink -f ${KW_CONFIG_DIR:-.})
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/firmware/$installedname
else
	fwdir=/lib/firmware/$installedname
fi

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

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

mkdir $tmpdir/firmware-list

code=0
# 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
	# preprocess file, handle includes and excludes and sort so that
	# the joins work, no matter what the order of the input.
	kernel-wedge preprocess $fwlistdir/$i $fwdir | sort > $tmpdir/firmware-list/$i

	# deal with firmware marked as optional and other transformations
	processfirmware $tmpdir/firmware-list/$i $fwdir || code=$?

	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/firmware/$installedname
			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
exit $code
