#!/bin/sh -e

# Detects packages built on mips(el) that are linked against libgfortran3
# which include binaries satisfying the following constraints:
# a) use "sincos{,f,l}" functions from libm
# b) use functions from gfortran (detected with "nm -D | grep _gfortran")

# This script requires wget and dctrl-tools packages.

# Uncomment the following if you have already downloaded and unpacked the
# Packages files and .debs so that you won't have to re-download everything:
#DO_DOWNLOAD=no

BASEURL=ftp://ftp.de.debian.org/debian/
COMPONENTS="main contrib non-free"
ARCHES="mips mipsel"

[ "x$DO_DOWNLOAD" = xno ] || rm -rf debs unpacked Packages*
rm -rf file-lists results.*.txt
mkdir -p debs unpacked file-lists

if [ ! "x$DO_DOWNLOAD" = xno ] ; then
	for arch in $ARCHES; do
		for comp in $COMPONENTS; do
			wget $BASEURL/dists/sid/$comp/binary-$arch/Packages.bz2
			bunzip2 -c Packages.bz2 >> Packages-$arch
			rm Packages.bz2
		done
	done
fi

for arch in $ARCHES ; do
	gf_pkgs="$(grep-dctrl -F Depends libgfortran3 -s Package \
			< Packages-$arch | cut -f 2 -d ' ')"
	for pkg in $gf_pkgs ; do
		file="$(grep-dctrl -F Package $pkg --exact-match \
			-s Filename < Packages-$arch | cut -f 2 -d ' ')"
		deb="$(basename "$file")"
		dir="${deb%.deb}"
		echo Processing package $pkg for $arch...
		if [ ! "x$DO_DOWNLOAD" = xno ] ; then
			wget -P debs "$BASEURL/$file"
			dpkg -x debs/"$deb" unpacked/"$dir"
		fi

		result="$(find unpacked/$dir -type f -exec sh -c "eval \
			file  \"{}\" | grep -q ELF && \
			nm -D \"{}\" | grep -q ' U sincos' && \
			nm -D \"{}\" | grep -q ' U _gfortran' && \
			echo  \"{}\"" \; 2> /dev/null )"
		if [ -n "$result" ] ; then
			echo "$result" | sed 's,^[^/]*/[^/]*,,' \
				> file-lists/$dir.list
			
			source="$(dpkg -I debs/$deb | grep '^ Source: ' | \
				awk '{print $2}')"
			[ -n "$source" ] || source="$(dpkg -I debs/$deb | \
				grep '^ Package: ' | awk '{print $2}')"

			# take care to check source versions that differ from
			# that of binary package
			version="$(dpkg -I debs/$deb | grep '^ Source: ' | \
				awk '{print $3}' | tr -d '()')"
			[ -n "$version" ] || version="$(dpkg -I debs/$deb | \
				grep '^ Version: ' | awk '{print $2}')"

			echo "$source/$version" >> results.$arch.txt
		fi
	done
done

echo
for arch in $ARCHES ; do
	echo "Sorting results.$arch.txt..."
	sort results.$arch.txt | uniq > tmp
	mv -f tmp results.$arch.txt
done

echo
echo "Done."
