#!/bin/sh -e

logmsg() { logger -t debian-edu-install/base-installer "info: $*"; }
log() { logmsg "info: $*"; }

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

# remove the debianfreespace logical volume.  Doing it before
# installing packages, to make it possible to resize volumes on the
# fly during installation.
# FIXME check if partman support allocating free space and use this instead
VG=$(mount | sed -n 's@^/dev/mapper/\(.*\)-root on /target.*@\1@p')
if [ -e /dev/$VG/debianedufreespace ] ; then
    if grep -q /debianedufreespace /proc/mounts; then
        umount /target/debianedufreespace
    fi
    lvremove -f /dev/$VG/debianedufreespace
    grep -v /debianedufreespace /target/etc/fstab > /target/etc/fstab.new && \
      mv /target/etc/fstab.new /target/etc/fstab
    if [ -d /target/debianedufreespace ] ; then
	rmdir /target/debianedufreespace
    fi
fi

# Need to do this here, as apt need to work via Squid to install
# debian-edu-config where the permanent file is included.
# FIXME check if this still is needed.  See BTS report #565555.
log "adding /etc/apt/apt.conf.d/90squid-di working around bug in Squid."
cat > /target/etc/apt/apt.conf.d/90squid-di <<EOF
// Avoid Squid handing out corrupt packages, solves Skolelinux bug #1419.
Acquire::http::Pipeline-Depth 0;
EOF

log "setting up aptkey"
if [ -f /usr/share/keyrings/archive.gpg -a ! -f /target/etc/apt/trusted.gpg ] ; then
    log "creating /etc/apt in target"
    mkdir -p /target/etc/apt
    log "copying archive.gpg as trusted.gpg under /etc/apt in target"
    cp /usr/share/keyrings/archive.gpg /target/etc/apt/trusted.gpg
else
    test -f /usr/share/keyrings/archive.gpg || \
        log "missing archive.gpg keyring in the installer"
    test -f /target/etc/apt/trusted.gpg && \
        log "trusted.gpg already exists under /etc/apt in target"
fi

disable_exception
