#!/bin/sh
### BEGIN INIT INFO
# Provides:          xdebian-edu-firstboot
# Required-Start:    $remote_fs $all
# Required-Stop:
# Should-Start:      $x-display-manager xdm kdm gdm wdm slim
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Check the Debian Edu installation after first boot
# Description:       Run the self test and report any errors found.
#                    Install this as /etc/rc2.d/99xdebian-edu-firstboot
### END INIT INFO
#
# Author: Petter Reinholdtsen
# Date:   2006-09-22
#

# only run if package is installed (debian policy 9.3.2)
test -f /usr/lib/debian-edu-install/version || exit 0

. /lib/lsb/init-functions

firstboot_file=/etc/debian-edu/xdebian-edu-firstboot

set -e

run_testsuite() {
    log_begin_msg "Collecting testsuite results"
    logfile=/var/log/installer/debian-edu-install-testsuite

    temp_dir=$(mktemp -d)
    errfile=$temp_dir/errors

    nice debian-edu-test-install > $logfile 2>&1

    # find error and partition resize messages in the d-i log and the
    # self test
    if [ -f /var/log/installer/syslog  ] ; then
        # remove syslog prefix
        # Ignore normal errors from wget commands used to test it
        # mirrors are available [pere 2010-07-22].
        egrep 'error:|fsautoresize' /var/log/installer/syslog | \
	    grep -v 'wget: server returned error: HTTP/1.0 404 Not Found' | \
	    grep -v 'wget: server returned error: HTTP/1.1 404 Not Found' | \
	sed 's/.*error: /error: /g' > $errfile
    fi
    grep error: $logfile >> $errfile || true

    if [ -s $errfile ] ; then
        log_end_msg 1 || true
        log_begin_msg "Reporting errors found"
        if $0 report-errors $errfile ; then
            log_end_msg 0 || true
        else
            log_end_msg 1 || true
        fi
    else
        log_end_msg 0 || true
        $0 report-success || true
    fi
    rm $errfile
    rmdir $temp_dir
}

do_start() {
    logger -t debian-edu-install "Executing xdebian-edu-firstboot"

    # The parts updating LTSP and readahead was moved to
    # debian-edu-config, this hook made it possible.
    if [ -x /usr/share/debian-edu-config/tools/run-at-firstboot ] ; then
	log_begin_msg "Running debian-edu-config run-at-firstboot"
	/usr/share/debian-edu-config/tools/run-at-firstboot 
	log_end_msg 0 || true
    fi

    # only run the testsuite and report errors during development, not
    # during production
    if [ -f /etc/debian-edu/config ] ; then . /etc/debian-edu/config ; fi
    if [ true = "$TESTINSTALL" ]; then
	run_testsuite
    else
	log_begin_msg "Not collecting testsuite results"
	log_end_msg 0 || true
    fi

    # Create firstboot file to prevent it from being run again
    touch "$firstboot_file"
}

prepare_debconf() {
    # Try to get debconf to pop up the dialog on top of the display
    # manager.  Need to do this before starting debconf.

    # This is generated by kdm
    candidate="`ls -tr /var/run/xauth/* 2>/dev/null|tail -1`"

    # gdm, lightdm
    candidate="$candidate /var/lib/gdm/:0.Xauth /var/lib/lightdm/.Xauthority"

    # gdm3
    for f in /var/run/gdm3/auth-for-Debian-gdm*/database ; do
	candidate="$candidate $f"
    done

    XAUTHORITY=
    for f in $candidate ; do
	if XAUTHORITY=$f DISPLAY=:0 xauth list >/dev/null 2>&1 &&
	    XAUTHORITY=$f DISPLAY=:0 xhost > /dev/null 2>&1 ; then
	    XAUTHORITY=$f
	    break
	fi
    done

    if [ "$XAUTHORITY" ] ; then
        # Try to use kde frontend (require libqt-perl) or gnome frontend
        # (libgtk2-perl).  debconf will fall back to dialog if either
        # frontend fails to start.  The frontend need to be set before
        # confmodule is sourced to have effect.
        DISPLAY=:0
        # TODO: find graphical variant that works with dialog frontend?
        if [ -f "/usr/lib/perl5/Qt.pm" ]; then
            # use kde frontend
            export DEBIAN_FRONTEND=kde
        elif [ -f "/usr/lib/perl5/Gtk2.pm" ]; then
            # fall back to gnome
            export DEBIAN_FRONTEND=gnome
        fi
        export XAUTHORITY DISPLAY
    fi

    . /usr/share/debconf/confmodule

    # Disable usplash if enabled and not using the X display, to get
    # the debconf dialog to show up.  Need to do this after the
    # $DISPLAY variable is set up, to detect if the X connection is
    # working.
    if [ -z "$DISPLAY" ] && type usplash_write >/dev/null 2>&1; then
        clear >/dev/tty8
        /sbin/usplash_write QUIT
        chvt 8
    fi
}

cleanup_debconf() {
    # Move back to tty1, to get the login prompt
    if [ -z "$DISPLAY" ] && type usplash_write >/dev/null 2>&1; then
        chvt 1
    fi
}

report_errors() {
    errfile="$2"

    prepare_debconf $@

    # Quick fix to make sure all error entries at least are
    # displayed.  The correct fix is to find out how to replace a
    # debconf variable with multiline content.  not sure why I
    # need to change this in to one long line
    errors=`cat $errfile | sed 's/$/, /g' | tr -d "\n" | sed 's/, $//'`

    # Take a look at how CURRENT_CONFIG is built up in
    # partman/partman-lvm/choose_partition/lvm/do_option

    db_subst debian-edu-install/errors-found ERRORS "$errors"

    db_fset debian-edu-install/errors-found seen false
    db_input critical debian-edu-install/errors-found || [ $? -eq 30 ]
    db_go

    cleanup_debconf
}

report_success() {
    prepare_debconf $@

    log_begin_msg "Reporting successful installation"

    db_input critical debian-edu-install/no-errors-found || [ $? -eq 30 ]
    db_go

    log_end_msg 0 || true

    cleanup_debconf
}

case "$1" in
    start)
        if [ ! -f "$firstboot_file" ]; then
            do_start
        fi
        ;;
    stop|force-reload|restart)
        ;;
    report-errors)
        # Need to pass all arguments, to get debconf re-exec to work
        report_errors $@
        ;;
    report-success)
        # Need to pass all arguments, to get debconf re-exec to work
        report_success $@
	;;
    *)
        echo "Usage: /etc/init.d/xdebian-edu-firstboot {start|stop|restart|force-reload}"
        exit 1
        ;;
esac

exit 0
