#!/bin/sh

. /usr/share/debconf/confmodule

CDMNT=/cdrom

cmd="$1"
shift

case "x$cmd" in
    xconfig)
        for f in include exclude; do
            if [ -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
            exit 1
        fi
        ;;

    xpackages)
        rm -f "$1"
        touch "$1"
        # We can use 'stable' since there are always symlinks
        Release="$CDMNT/dists/stable/Release"
        ARCH=`udpkg --print-architecture`
        components="`grep ^Components: $Release | cut -d' ' -f2-`"
        ret=1
        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
                    continue
                fi
                Packages="$CDMNT/dists/stable/$pkgfile"
                if [ ! -e "$Packages" ]; then
                    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 high "$T" || true
		db_go || true
		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
        ;;

    *)
        # unknown command
        exit 1
esac
