#!/bin/sh -e

. /usr/share/debconf/confmodule

FLOPPYMNT=/floppy

ask_dev() {
	DEVS=""
	for dev in `find /dev/floppy /dev/scsi /dev/ide /dev/disc`; do
		# TODO if sfdisk or something similar were available, we could
		# do this:
		#        SIZE=sfdisk -s $DEV
		#        if [ "$SIZE" -eq '1440' -o "$SIZE" -eq '2880' ]; then
		if [ -b "$dev" ]; then
			if [ -z "$DEVS" ]; then
				DEVS="$dev"
			else
				DEVS="$DEVS, $dev"
			fi
		fi
	done
	db_subst retriever/floppy/device DEVS $DEVS
	db_input high retriever/floppy/device
	db_go 
	db_get retriever/floppy/device
	if [ "$RET" = Cancel ]; then
		exit 1
	fi
	echo $RET
}

mountfloppy() {
	if ! mount | cut -d' ' -f3 | grep -q '^/floppy$'; then
		# This is a good reasonable default, but will fail for
		# USB floppys.
		FLOPPYDEV=/dev/floppy/0
		
		if [ ! -e $FLOPPYDEV ]; then
			modprobe floppy >> /var/log/messages 2>&1 || true
		fi
	
		if ! grep -q ^vfat /proc/modules ; then
			modprobe vfat >> /var/log/messages 2>&1 || true
		fi

		if [ ! -e "$FLOPPYDEV" ] || ! mount $FLOPPYDEV -tauto $FLOPPYMNT; then
			# Cannot find a device, or found the wrong device.
			# Ask for help from the user and try it again.
			FLOPPYDEV=$(ask_dev)
			mount $FLOPPYDEV -tauto $FLOPPYMNT
		fi
	fi
}

cmd="$1"
shift

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

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

	xpackages)
		# generate a Packages file based on what udebs are on the
		# floppy
		mountfloppy
		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 $FLOPPYMNT/*.deb $FLOPPYMNT/*.udeb $FLOPPYMNT/*.ude; do
			if [ -f "$filename" ]; then
				FILES="$FILES $filename"
				FILE_COUNT=$(expr $FILE_COUNT + 1)
			fi
		done
		if [ "$FILE_COUNT" = 0 ]; then
			# Probably not a legitimate driver floppy.
			exit 1
		fi
		# This could take a while, so a progress bar.
		db_progress START 0 $FILE_COUNT retriever/floppy/packages/progress
		for filename in $FILES; do
			udpkg -f "$filename" | sed 's/Priority: .*/Priority: standard/' >> "$1"
			path="`echo "$filename" | sed 's,^/floppy/,,'`"
			echo "Filename: $path" >> "$1"
			echo >> "$1"
			db_progress STEP 1
		done
		db_progress STOP
	;;

	xerror)
		umount $FLOPPYMNT || true

		T="retriever/floppy/error"
		db_set "$T" true
		db_input high "$T" || true
		db_go || true
		db_get "$T"
		if [ "$RET" = true ]; then
			exit 0
		else
			exit 2
		fi
	;;
	
	xcleanup)
		umount $FLOPPYMNT || true
		rm -f /var/cache/anna/include
		rm -f /var/cache/anna/exclude
	;;

	*)
		# unknown command
		exit 1
	;;
esac
