#!/bin/bash

IS_TEXT="/usr/libexec/initial-setup/initial-setup-text"
IS_GRAPHICAL="/usr/libexec/initial-setup/initial-setup-graphical"
IS_UNIT=initial-setup.service

# systemd targets
GRAPHICAL_TARGET="graphical.target"
CURRENT_DEFAULT_TARGET="$(systemctl get-default)"

WINDOWMANAGER_SCRIPT="/usr/libexec/initial-setup/firstboot-windowmanager"

START_GUI_COMMAND="/usr/bin/xinit ${WINDOWMANAGER_SCRIPT} ${IS_GRAPHICAL} --no-stdout-log -- /usr/bin/Xorg :9 -ac -nolisten tcp"

# check if graphical Initial Setup is installed
if [ -f ${IS_GRAPHICAL} ]; then
    # don't run the GUI on text-only systems (default.target != graphical.target),
    # users are not expecting a graphical interface do start in such case
    # and there might not even be any displays connected
    if [ "$CURRENT_DEFAULT_TARGET" == "$GRAPHICAL_TARGET" ]; then
        echo "Starting Initial Setup GUI" | systemd-cat -t initial-setup -p 6
        # Make look and feel the same in all DEs and avoid graphical artefacts with some themes
        export GTK_THEME=Adwaita:light
        ${START_GUI_COMMAND}
    else
        echo "Initial Setup GUI is installed, but default.target != graphical.target" | systemd-cat -t initial-setup -p 5
        echo "Starting Initial Setup TUI" | systemd-cat -t initial-setup -p 6
        ${IS_TEXT} --no-stdout-log
    fi
else
    echo "Starting Initial Setup TUI" | systemd-cat -t initial-setup -p 6
    ${IS_TEXT} --no-stdout-log
fi

# check if the Initial Setup run was successful by looking at the return code
if [ $? -eq 0 ]; then
    echo "Initial Setup finished successfully, disabling" | systemd-cat -t initial-setup -p 6
    systemctl -q is-enabled $IS_UNIT && systemctl disable $IS_UNIT
    echo "Initial Setup has been disabled" | systemd-cat -t initial-setup -p 6
else
    echo "Initial Setup failed, keeping enabled" | systemd-cat -t initial-setup -p 3
    exit 1
fi

# Anaconda post-install script removes Anaconda and initial-setup
# if it detects that initial-setup is not needed
if ! grep -q removeinitialsetup=0 /proc/cmdline; then
	list="$(rpm -qa --qf '%{name} ' anaconda* initial-setup*)"
	if [ -n "$list" ]; then
		echo "Removing initial-setup and Anaconda" | systemd-cat -t initial-setup -p 6
		dnf -y remove $list
	fi
fi
