#!/bin/sh

. /usr/share/debconf/confmodule

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

CDMNT=/cdrom

cmd="$1"
shift

case "x$cmd" in
    xconfig)
        info "Retrieving udeb include and exclude file."
        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
            error "Unable to find '$1'."
            exit 1
        fi
        ;;

    xpackages)
        info "Retrieving package list."
        rm -f "$1"
        touch "$1"
	if db_get mirror/suite; then
		suite=$RET
	else
		suite=stable
	fi
        Release="$CDMNT/dists/$suite/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
                    warning "Unable to find $pkgfile in $Release."
                    continue
                fi
                Packages="$CDMNT/dists/$suite/$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
        ;;

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