#!/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 lightdm
# Default-Start:     2 3 4 5
# Default-Stop:
# X-Interactive:     true
# 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

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() {
    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 if
        # mirrors are available [pere 2010-07-22].
        # Ignore also samba-ad-dc error (unused atm) [schweer 2018-11-05].
        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' | \
	    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 1000 by default).
    firstuser=$(getent passwd | grep 1000 | cut -d':' -f1)
    username=$(getent passwd | grep 1000 | 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

        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

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

    # only run the testsuite and report errors if requested via kernel
    # command line param 'testinstall'.
    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
}

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

    log_begin_msg "Reporting successful installation"

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

    log_end_msg 0 || true
}

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}"
        disable_exception
        exit 1
        ;;
esac

disable_exception
exit 0
