#!/bin/sh

. /usr/share/debconf/confmodule

log() {
	logger -t cdrom-retriever "$@"
}
error() {
	log "error: $@"
}
warning() {
	log "warning: $@"
}

CDMNT=/cdrom
ARCH=`udpkg --print-architecture`

cmd="$1"
shift

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

	xretrieve)
		if [ -e $CDMNT/$1 ]; then
			ln -sf $CDMNT/$1 "$2"
			exit $?
		else
			error "Unable to find '$1'."
			exit 1
		fi
        ;;

	xpackages)
		rm -f "$1"
		touch "$1"
		if db_get cdrom/codename && [ "$RET" ]; then
			codename=$RET
		else
			# Not really nice defaulting codename to a suite...
			codename=stable
		fi
		Release="$CDMNT/dists/$codename/Release"
		components="`grep ^Components: $Release | cut -d' ' -f2-`"
		ret=1
		if [ -z "$components" ]; then
			error "No components listed in $Release."
			exit 1
		fi
		for comp in $components; do
			for ext in '' '.gz'; do
				pkgfile="$comp/debian-installer/binary-$ARCH/Packages$ext"
				line=`grep $pkgfile\$ $Release 2>/dev/null`
				if [ $? != 0 ]; then
					warning "Unable to find $pkgfile in $Release."
					continue
				fi
				Packages="$CDMNT/dists/$codename/$pkgfile"
				if [ ! -e "$Packages" ]; then
					warning "File $Packages does not exist."
					continue
				fi
				# TODO: Verify the integrity
				if [ "$ext" = '' ]; then
					cat "$Packages" >> "$1"
				elif [ "$ext" = .gz ]; then
					zcat "$Packages" >> "$1"
				fi
				ret=0
				break
			done
		done
		exit $ret
        ;;

	xerror)
		T="retriever/cdrom/error"
		db_input critical "$T" || true
		if ! db_go; then
			exit 2
		fi
		db_get "$T"
		if [ "$RET" = true ]; then
			exit 0
		else
			exit 2
		fi
	;;
	
	xcleanup)
		rm -f /var/cache/anna/include
		rm -f /var/cache/anna/exclude
	;;

	*)
		error "Unknown command '$cmd'."
		exit 1
	;;
esac
