#!/bin/sh

# dedup the cache, removing from it what we have on
# ISOs, or more precisely:
# remove from /var/local/cache filesystem, files of type ordinary file
# where name matches '*.deb' where we find under filesystems mounted
# at IMD files of type ordinary file where name and data
# matches.

set -e

IMD="$(mktemp -d)" # ISOs Mount Directory
find /var/local/ISOs/ -xdev -name 'debian*.iso' -type f ! -size 0 \
	-print |
sed -e '
	s/^.*\/\(debian[^\/]*\.iso\)$/\1 &/
' |
while read b p
do
	mkdir "$IMD/$b" &&
	mount -t iso9660 -o loop,ro,nosuid,nodev "$p" "$IMD/$b"
done

find "$IMD"/*/ /var/local/cache -xdev -name '*.deb' -type f -print 2>>/dev/null |
sed -e 's/^.*\/\([^/]*\.deb\)$/\1 &/' |
sort |
awk '
	{
		if(NR==1){
			printf("%s",$0);
			b=$1;
		}else{
			if($1==b){
				printf(" %s",$2);
			}else{
				print "";
				printf("%s",$0);
				b=$1;
			}
		}
	}
	END{print ""}
' |
while read b ps
do
	pn=
	pc=
	for p in $ps
	do
		case "$p" in
			"$IMD"/*)
				pn="${pn:+$pn }$p"
			;;
			/var/local/cache/*)
				pc="${pc:+$pc }$p"
			;;
		esac
	done
	[ x"$pn" != x ] && [ x"$pc" != x ] && {
			for t in $pc
			do
				for s in $pn
				do
					cmp "$s" "$t" 2>>/dev/null && {
						rm "$t"
						break 2
					}
				done
			done
	}
done

mount -t iso9660 |
awk '{print $3;}' |
tac |
while read mp
do
	case "$mp" in
		"$IMD"/*)
			umount "$mp"
			rmdir "$mp"
		;;
	esac
done
rmdir "$IMD"
