#!/bin/sh

mirror="http://ftp2.de.debian.org/debian"
tempDir="/tmp/getDebianTemplates$$"
arch="i386"
release="jessie"
templateDir="`pwd`/templates-$release-$arch"

mkdir -p $tempDir $templateDir





#Get the list of all packages for a release and store in getDebianTemplates.filelist
getFileList()
{
	rm getDebianTemplates.filelist 2> /dev/null
	for branch in main contrib non-free
	do
		wget $mirror/dists/$release/$branch/binary-$arch/Packages.xz -O "$tempDir/Packages.xz"
		xzcat -d "$tempDir/Packages.xz" | grep Filename | cut -d' ' -f2 >> getDebianTemplates.filelist
	done
}





#Download and extract the templates of all Debian packages listed in getDebianTemplates.filelist
getTemplates()
{
	for package in `cat getDebianTemplates.filelist`
	do
		rm "$tempDir/*" 2> /dev/null
		name=`basename $package .deb`
		templateFile="$templateDir/$name.templates"

		if [ ! -e $templateFile ]
		then
			echo ">>> $name"

			wget -q "$mirror/$package" -O "$tempDir/cur.deb"
			ar x "$tempDir/cur.deb"
			tar -xz -C$tempDir -f control.tar.gz
			if [ -e "$tempDir/templates" ]
			then
				mv "$tempDir/templates" $templateFile
			else
				touch $templateFile
			fi
			rm control.tar.gz data.tar.gz debian-binary
		fi
	done
}





#Removes all template files that are empty
cleanZeroFiles()
{
	cd $templateDir
	find -size 0 | xargs rm
}

getFileList
getTemplates
cleanZeroFiles

rm -r $tempDir
