#!/bin/bash

if [ "$1" == "--help" ]; then
	echo "old source files"
	exit 1
fi

# fake variable for fwmakepkg
CHROOT=1

. ./functions.sh
. /etc/makepkg.conf
. /usr/lib/frugalware/fwmakepkg

reset_env () {
	unset archs install nobuild options pkgname pkgver pkgextraver source sha1sums
	for k in `set| grep -E '^(_F_|USE_)'|sed 's/\(=.*\| ()\)//'`; do unset $k; done

	export Fpkgversep='-' startdir=`pwd`
}

if [ "$1" == "--remove" ]; then
	remove="y"
	shift
fi
sdir=..

newsrcs=`mktemp`
gitsrcs=`mktemp`
oldsrcs=`mktemp`
allsrcs=`mktemp`

cd $sdir

CWD=`pwd`
for i in `find source -name FrugalBuild`
do
	cd `dirname $i` || continue
	reset_env
	. ./FrugalBuild || echo "errors parsing the FrugalBuild"
	if [ ! -z "$pkgname" -a ! "$nobuild" -a ! "`check_option NOBUILD`" ]; then
		for j in ${archs[@]}
		do
			CARCH=$j
			reset_env
			. ./FrugalBuild || echo "errors parsing the FrugalBuild for $pkgname"
			for k in "${source[@]}" "${signatures[@]}"
			do
				# skip our own sources
				[[ "$k" =~ "http://ftp.frugalware.org" ]] \
					|| echo "`pwd|sed \"s|$CWD/||\"`/`strip_url $k`" >>$newsrcs
			done
		done
	fi
	cd - >/dev/null
done
cat $newsrcs |sort -u >$newsrcs.sorted
mv -f $newsrcs.sorted $newsrcs

find source ! -type d ! -name Changelog -a ! -name *.log.bz2 -a ! -name *.html |sort >$allsrcs
cd source
git ls-tree --name-only -r HEAD |sed 's|^\(.\)|source/\1|'|sort >$gitsrcs
cd ..

diff -u $allsrcs $gitsrcs |grep ^-[^-] |sed 's/^-//' >$oldsrcs

for i in `diff -u $oldsrcs $newsrcs |grep ^-[^-] |sed 's/^-//'`
do
	[ -z "$remove" ] && echo $i || rm -v $i
done
rm -f $newsrcs $gitsrcs $oldsrcs $allsrcs
