#!/bin/sh
set -e

. /usr/share/debconf/confmodule
. /lib/chroot-setup.sh

# This code is copied from chroot-setup.sh, and is needed until after a d-i
# release whose initrds contain a sufficiently new version of di-utils.
if ! type chroot_cleanup_localmounts >/dev/null 2>&1; then
    # Variant of chroot_cleanup that only cleans up chroot_setup's mounts.
    chroot_cleanup_localmounts () {
        rm -f /target/usr/sbin/policy-rc.d
        mv /target/sbin/start-stop-daemon.REAL /target/sbin/start-stop-daemon
        if [ -x /target/sbin/initctl.REAL ]; then
            mv /target/sbin/initctl.REAL /target/sbin/initctl
        fi

        # Undo the mounts done by the packages during installation.
        # Reverse sorting to umount the deepest mount points first.
        # Items with count of 1 are new.
        for dir in $( (cat /tmp/mount.pre /tmp/mount.pre /tmp/mount.post ) | \
                 sort -r | uniq -c | grep "^[[:space:]]*1[[:space:]]" | \
                 sed "s/^[[:space:]]*[0-9][[:space:]]//"); do
            if ! umount $dir; then
                logger -t $0 "warning: Unable to umount '$dir'"
            fi
        done
        rm -f /tmp/mount.pre /tmp/mount.post

        rm -f /var/run/chroot-setup.lock
    }
fi

file="$1"

if [ ! -e /cdrom/.disk/cd_type ] || [ ! -e /var/lib/install-cd.id ]; then
    exit 0
fi

# Various different image types look different here:
#
# Image Type                       cd_type
###################################################
# netinst                          "not_complete"
# full CD sets (default desktop)   "full_cd"
# desktop-specific CD images       "full_cd/single"
# DVD                              "dvd"
# bluray                           "bluray"
# multi-arch CD/DVD                "not_complete"
# live                             "live"
#
# It can make sense to offer to scan more media here in most cases,
# but... on live or blu-ray it's unlikely to help; the
# desktop-specific image is designed specifically to work with only a
# single image. Hopefully the following makes sense.
#
# Images written to USB pen drives still need better support
# too... :-(
cd_type=$(cat /cdrom/.disk/cd_type)
case "$cd_type" in
    live)
    exit 0
    ;;
    full_cd/single)
    exit 0
    ;;
    bluray*)
    exit 0
    ;;
esac

get_label() {
    LC_ALL=C $logoutput --pass-stdout $chroot $ROOT \
        apt-cdrom ident < /dev/null | grep "^Stored label:" | head -n1 | \
        sed "s/^[^:]*: //"
}

logoutput=""
if [ "$CATCHLOG" ]; then
    logoutput="log-output -t apt-setup"
fi

chroot=
if [ "$ROOT" ]; then
    chroot=chroot

    # We can only change CDs if current CD is unmounted
    $logoutput umount /cdrom || true

    chroot_setup
    # Horrible hack to let us call a subprocess that also sources the
    # confmodule, since chroot_setup tears down debconf state.
    export DEBIAN_HAS_FRONTEND=1
    export DEBCONF_REDIR=1
    # Needed until after a d-i release with new enough di-utils.
    mountpoints > /tmp/mount.post
    trap chroot_cleanup_localmounts EXIT HUP INT QUIT TERM
fi

tmp=$($chroot $ROOT tempfile)

cd_label=$(tail -n1 /var/lib/install-cd.id)
db_subst apt-setup/cdrom/set-first LABEL "$cd_label"
db_input high apt-setup/cdrom/set-first || true
if ! db_go; then
    if [ "$ROOT" ]; then
        load-install-cd "$ROOT"
    fi
    exit 10
fi
db_get apt-setup/cdrom/set-first

while [ "$RET" = true ]; do
    cd_label=$(get_label)
    # Hmm. The greps could fail if a label contains regexp control chars...
    if [ "$cd_label" ] && \
       (grep "^deb cdrom:\[$cd_label\]" $file || \
        grep "^deb cdrom:\[$cd_label\]" $ROOT/etc/apt/sources.list.new); then
        template=apt-setup/cdrom/set-double
        db_subst $template LABEL "$cd_label"
    else
        # apt-cdrom can be interactive, avoid that
        if $logoutput $chroot $ROOT apt-cdrom add \
           -o Dir::Etc::SourceList=$tmp \
           </dev/null; then
            cat $ROOT$tmp >> $file

            # Label is assigned by apt-cdrom add, so get again
            cd_label=$(get_label)
            template=apt-setup/cdrom/set-next
            db_subst $template LABEL "$cd_label"
        else
            template=apt-setup/cdrom/set-failed
        fi
        rm -f $ROOT$tmp $ROOT$tmp~
    fi

    db_input critical $template || true
    if ! db_go; then
        if [ "$ROOT" ]; then
            load-install-cd "$ROOT"
        fi
        exit 10
    fi
    db_get $template
done

# Make sure the installation CD is loaded again
if [ "$ROOT" ]; then
    load-install-cd "$ROOT"
fi
