#!/bin/sh

set -e

if ! which lsb_release >/dev/null 2>&1; then
    echo >&2 install the lsb-release package to run this script
    exit 1
fi

esslist=essential-packages-list
case "`lsb_release -is`" in
    Debian)
	dist='sid'
	#mirror_list=http://ftp.debian.org/debian
	mirror_list="$mirror_list http://ftp.de.debian.org/debian"
	mirror_list="$mirror_list http://ftp.debian-ports.org/debian"
	# add archs which are not yet/anymore in archtable
	# remove discontinuted archs (e.g. arm, sh)
	arches=`( \
	    awk '($1 != "" && $1 !~ /^#/) {print $2}' /usr/share/dpkg/archtable; \
	    echo 'armhf m68k ppc64 powerpcspe sh4 sparc64 x32'; \
	  ) \
	  | sort -u | egrep -v '^(arm|sh)$'`
	;;
    Ubuntu)
	dist=`lsb_release -cs`
	mirror_list="$mirror_list http://archive.ubuntu.com/ubuntu"
	mirror_list="$mirror_list http://ports.ubuntu.com/ubuntu-ports"
	arches='armhf amd64 i386 powerpc'
	;;
    *)
	dist='n/a';;
esac


for arch in $arches
do
	if [ ! -f Packages-$arch ]
	then
		for mirror in $mirror_list; do
			if wget -O Packages-$arch.bz2 $mirror/dists/$dist/main/binary-$arch/Packages.bz2
			then
				bunzip2 -f Packages-$arch.bz2
				break
			else
				rm -f Packages-$arch
			fi
		done
	fi
	if [ -f Packages-$arch ]
	then
		printf > $esslist-$arch \
			'This list was generated on %s for %s\n' \
			"`LANG=C date`" "$arch"
		echo >> $esslist-$arch \
			'It contains a list of essential packages' \
			'(which are also build-essential).'
		echo >> $esslist-$arch

		grep-status -FEssential -sPackage -ni yes Packages-$arch \
			| sort >> $esslist-$arch
	else
		echo "No essential packages list is available" \
			"for $arch in $dist" > $esslist-$arch
	fi
done
rm -f Packages-*
