#!/bin/sh
#
# debian-edu-testsuite - Check the Debian Edu installation after first boot
#
# Run the self test and report any errors found.
#
# Author: Petter Reinholdtsen
#

info() {
    logger -t debian-edu-install "info: $@"
}

error() {
    logger -t debian-edu-install "error: $@"
}

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

run_testsuite() {
    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 if
        # mirrors are available [pere 2010-07-22].
        # Ignore also samba-ad-dc error (unused atm) [schweer 2018-11-05].
        grep -E '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' | \
	    grep -v 'samba-ad' | \
	sed 's/.*error: /error: /g' > $errfile
    fi
    # The a param is now needed to find all errors [schweer 2018-11-05].
    grep -a error: $logfile >> $errfile || true

    if [ -s $errfile ] ; then
    content=$(cat $errfile)
    # Send error report via mail to first user (who has uid 2000 by default).
    firstuser=$(getent passwd 2000 | cut -d':' -f1)
    username=$(getent passwd 2000 | cut -d':' -f5)

            cat << EOF | /usr/lib/sendmail $firstuser
Subject: Test status

Hello $username,

these are the test results you requested by adding 'testinstall' as
additional kernel commandline parameter. They have been collected by running
the testsuite and searching in the /var/log/installer directory.

$content

(Sent from the Debian Edu first boot script.)

EOF

        $0 report-errors $errfile || true
    else
        $0 report-success || true
    fi
    rm $errfile
    rmdir $temp_dir
}

prepare_debconf() {
    # Try to get debconf to pop up the dialog on top of the display
    # manager.  Need to do this before starting debconf.
    if [ ! "$DEBIAN_HAS_FRONTEND" ] ; then
        # This is generated by sddm
	candidate="$(ls -tr /var/run/sddm/* 2>/dev/null|tail -1)"
        # lightdm
	candidate="$candidate /var/lib/lightdm/.Xauthority"

	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
            info "found X authority file $XAUTHORITY, trying to start debconf with X frontend."
            # Try to use gnome frontend (requires libgtk3-perl) or kde frontend
            # (requires debconf-kde-helper). debconf will fall back to dialog if
            # either frontend fails to start. The frontend needs to be set
            # before confmodule is sourced to have effect.
            DISPLAY=:0
            # TODO: find graphical variant that works with dialog frontend?
            if perl -MGtk3 -e 'exit 0' ; then
               # use gnome frontend
		export DEBIAN_FRONTEND=gnome
            elif [ -x /usr/bin/debconf-kde-helper ] ; then
               # use kde frontend
		export DEBIAN_FRONTEND=kde
            else
		info "unable to find usable debconf X frontend"
            fi
            export XAUTHORITY DISPLAY
	else
            info "no X detected, not showing test status, send email"
            return 1
	fi
    fi
    . /usr/share/debconf/confmodule
}

report_errors() {
    errfile="$2"

    prepare_debconf $@ || return

    # 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
}

report_success() {
    prepare_debconf $@ || return

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

case "$1" in
    run)
        run_testsuite
        ;;
    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: $0 {run|report-errors|report-success}"
        disable_exception
        exit 1
        ;;
esac
disable_exception
