#!/bin/sh
set -e

at_exit() {
    echo "info: terminating script"
    for m in $umount ; do
	echo info: umounting "$m"
	umount "$m"
    done
}

trap at_exit INT TERM EXIT

# Make sure temp directory setting do not leak into chroot.
chroot_run() {
    target=$1
    shift
    TMP= TMPDIR= TEMP= TEMPDIR= chroot $target "$@"
}

chroot_test() {
    echo
    echo "Installing Debian Edu chroot with profile $PROFILE and desktop $DESKTOP"
    echo
    cd $ADTTMP
    target=test-chroot
    suite=testing
    edusuite=jessie
    debootstrap $suite $target
    printf "#!/bin/sh\nexit 101\n" > $target/usr/sbin/policy-rc.d
    chmod a+rx $target/usr/sbin/policy-rc.d
    mount -t proc proc $target/proc
    umount="$target/proc"
    mount -t sysfs sysfs $target/sys
    umount="$target/proc $target/sys"

    # The bless script is recently part of the debian-edu-config package.
    if [ -x /usr/share/debian-edu-config/tools/debian-edu-bless ] ; then
	cp /usr/share/debian-edu-config/tools/debian-edu-bless \
	    $target/root/.
    else
	apt-get source debian-edu-config 2>&1
	cp debian-edu-config-*/share/debian-edu-config/tools/debian-edu-bless \
	    $target/root/.
    fi
    PROFILE=$PROFILE DESKTOP=$DESKTOP EDUSUITE=$edusuite \
	chroot_run $target sh -x /root/debian-edu-bless 2>&1

    # List packages with problems in Debian
    chroot_run $target apt-get install -y how-can-i-help
    chroot_run $target how-can-i-help --old

    umount $target/proc
    umount="$target/sys"
    umount $target/sys
    umount=""
    rm -rf $target
}

# Use predictable language setting.
# FIXME should try several to check language specific setup
LC_ALL=C
export LC_ALL

# Undo the effect of libpam-tmpdir in case it is active, and use the
# test specific temp directory.
export TMP=$ADTTMP
export TMPDIR=$ADTTMP
export TEMP=$ADTTMP
export TEMPDIR=$ADTTMP

echo "info: File system status (/proc/mounts):"
cat /proc/mounts
echo

# Install profiles in chroots, first the non-desktop ones
for profile in Minimal Main-Server; do
    PROFILE="$profile" chroot_test
done

# Then the desktop ones
for profile in Workstation Roaming-Workstation LTSP-Server Standalone; do
    for desktop in kde gnome lxde xfce mate ; do
        DESKTOP="$desktop" PROFILE="$profile" chroot_test
    done
done
