#! /bin/sh -e
#
# Last finishing touch before rebooting into the installed system.
#
# Try to avoid adding new code here.  Please put it in
# debian-edu-config in the
# /usr/share/debian-edu-config/d-i/finish-install script instead.

. /usr/share/debconf/confmodule
. /lib/debian-edu-common

log() {
    logger -t 13debian-edu-profile-udeb "$@"
}

error() {
    logger -t 13debian-edu-profile-udeb "error: $@"
}

at_exit() {
    error "script $0 terminated unexpectedly."
}
disable_exception() { trap - INT TERM EXIT; }
trap at_exit INT TERM EXIT

# Stop automatic lvm resize script set up before base-installer
# started.
rm -f /target/debian-edu-extend-file-systems

load_proxy_conf

# HACK part1: make the content of the BD available again and prevent unmounts
keep_cdrom_mountpoint_active=0
cd_type=$(cat /cdrom/.disk/cd_type)
case "$cd_type" in
    bluray*)
        keep_cdrom_mountpoint_active=1
        ;;
esac

if [ ${keep_cdrom_mountpoint_active} ]; then
    # /cdrom is mounted, but /target/media/cdrom isn't
    mount -o bin /cdrom /target/media/cdrom
    # Restore the 00NoMountCDROM file to prevent unmounting the BD
    # The file will be deleted by 90base-installer
    cat > /target/etc/apt/apt.conf.d/00NoMountCDROM << EOT
APT::CDROM::NoMount "true";
Acquire::cdrom {
  "/media/cdrom/" {
    Mount  "true";
    UMount "true";
  };
  AutoDetect "false";
}
EOT
fi

hook=/target/usr/share/debian-edu-config/d-i/finish-install
if [ -x $hook ] ; then
    log "Running debian-edu-config finish-install hook"
    $hook
else
    error "Unable to find $hook"
fi

edu-eatmydata-install disable

# HACK part2: configure apt for network access
# This can be moved to '/usr/lib/finish-install.d/92stop_using_the_bd_disk'
if [ ${keep_cdrom_mountpoint_active} ]; then
    log "Configure sources.list for network access"
    # Remove the CDROM entry
    sed -i "/^deb cdrom:/d" /target/etc/apt/sources.list
    # Append the usual content to sources.list
    db_get cdrom/codename
    codename="$RET"
    cat >> /target/etc/apt/sources.list << EOT
deb http://deb.debian.org/debian/ ${codename} main non-free-firmware
deb-src http://deb.debian.org/debian/ ${codename} main non-free-firmware
deb http://security.debian.org/debian-security ${codename}-security main non-free-firmware
deb-src http://security.debian.org/debian-security ${codename}-security main non-free-firmware
# ${codename}-updates, to get updates before a point release is made;
deb http://deb.debian.org/debian/ ${codename}-updates main non-free-firmware
deb-src http://deb.debian.org/debian/ ${codename}-updates main non-free-firmware
EOT
    # Activate the new sources.list
    # -> can only be done when a network connection is present, which is not guaranteed at this moment
    #in-target apt-get update
fi

disable_exception
exit 0
