#!/bin/sh -e

. /usr/share/debconf/confmodule

MNT=/media

cmd="$1"
shift

case "x$cmd" in
	xconfig)
		mountmedia driver
		for f in include exclude; do
			if [ -e $MNT/udeb_$f ]; then
				ln -sf $MNT/udeb_$f /var/cache/anna/$f
			fi
		done
	;;

	xretrieve)
		mountmedia driver
		if [ -e $MNT/$1 ]; then
			ln -sf $MNT/$1 "$2"
			exit $?
		else
			exit 1
		fi
	;;

	xpackages)
		# generate a Packages file based on what udebs are present
		mountmedia driver
		rm -f "$1"
		touch "$1"
		# Check for regular debs, udebs, and to be on the safe side,
		# check for *.ude files (msdos file names...)
		FILES=""
		FILE_COUNT=0
		for filename in $MNT/*.deb $MNT/*.udeb $MNT/*.ude; do
			if [ -f "$filename" ]; then
				FILES="$FILES $filename"
				FILE_COUNT=$(expr $FILE_COUNT + 1)
			fi
		done
		if [ "$FILE_COUNT" = 0 ]; then
			exit 1
		fi
		# This could take a while, so a progress bar.
		db_progress START 0 $FILE_COUNT retriever/media/packages/progress
		for filename in $FILES; do
			udpkg -f "$filename" | sed 's/Priority: .*/Priority: standard/' >> "$1"
			path="`echo "$filename" | sed 's,^/media/,,'`"
			echo "Filename: $path" >> "$1"
			echo >> "$1"
			db_progress STEP 1
		done
		db_progress STOP
	;;

	xerror)
		umount $MNT || true

		T="retriever/media/error"
		db_input critical "$T" || true
		db_go
		exit 2
	;;
	
	xcleanup)
		umount $MNT || true
		rm -f /var/cache/anna/include
		rm -f /var/cache/anna/exclude
	;;

	*)
		# unknown command
		exit 1
	;;
esac
