#!/bin/bash
#
# This is an sdm plugin for: graphics
#
# The plugin is called three times: for Phase 0, Phase 1, and post-install.
#

function loadparams() {
    source $SDMPT/etc/sdm/sdm-readparams
}

function delaydmenable() {
    #
    # Disable the display manager in $1 and set for re-enable during First Boot
    # $2=delayed target (either B3 or B4)
    #
    local dm="$1" bbh="$(getfinalbbh $2)"
    logtoboth "% Plugin $pfx: Display Manager '$dm' will be disabled when the system first boots"
    logtoboth "  The sdm FirstBoot process will re-enable it with boot_behavior '$bbh'"
    #SUDO_USER="$userx" raspi-config do_boot_behaviour B1 nonint > /dev/null 2>&1
    do_raspiconfig do_boot_behaviour B1
    systemctl set-default multi-user.target > /dev/null 2>&1
    setdelayedbbh $bbh
}

function delaylightdmenable() {
    #
    # $1 = "burning" if called from burn. "" otherwise
    #
    local burn="$1" aval
    logtoboth "> Plugin $pfx: Display Manager lightdm will be disabled when the system first boots"
    do_raspiconfig do_boot_behaviour B1
    systemctl set-default multi-user.target > /dev/null 2>&1
    [ $autologin -eq 1 ] && bbh="B4" || bbh="B3"
    aval=$(getfinalbbh "$bbh")
    if [ "$bbh" != "$aval" ]
    then
	logtoboth "% Plugin $pfx: Display Manager lightdm default boot behavior overridden by explicit setting '$aval'"
    else
	logtoboth "% Plugin $pfx: Desktop Autologin setting '$bbh' will be set after sdm FirstBoot"
	setdelayedbbh $bbh
    fi
}

function gfxcfgpostinstall() {

    if [ -d /etc/lightdm ]
    then
	logtoboth "> Plugin $pfx: Found Display Manager lightdm"
	#[ $reboot -eq 1 ] && delaylightdmenable || setlightdmautologin
	delaylightdmenable
    fi
    #
    # If xdm installed, disable it on console if requested
    #
    bbhandled=0
    if [ -d /etc/X11/xdm ]
    then
	logtoboth "> Plugin $pfx: Found Display Manager xdm"
	bbhandled=1
	# VV This overrides default LISTEN * ; 127.0.0.1 disables xdmcp finder, finder enabled with 0.0.0.0. By default xdmcp finder is enabled
	#echo "LISTEN 0.0.0.0" >> /etc/X11/xdm/Xaccess
	logtoboth "> Plugin $pfx: Update xdm.service so it can be enabled with systemctl"
	cp /lib/systemd/system/xdm.service /etc/systemd/system
	cat >> /etc/systemd/system/xdm.service <<EOF

[Install]
WantedBy=multi-user.target
EOF
	if [ $nodmconsole -eq 1 ]
	then
	    logtoboth "> Plugin $pfx: Disable xdm on console"
	    sed -i "s/\:0 local \/usr\/bin\/X :0 vt7 -nolisten tcp/\#\:0 local \/usr\/bin\/X :0 vt7 -nolisten tcp/"  /etc/X11/xdm/Xservers
	    [ -f /etc/sdm/0piboot/040-realvnc-server.sh ] && mv -f /etc/sdm/0piboot/040-realvnc-server.sh /etc/sdm/0piboot/.040-realvnc-server.sh
	    systemctl set-default multi-user.target
	    delaydmenable xdm B1
	else
	    delaydmenable xdm B3
	fi
    fi
    #
    # Ditto for wdm
    #
    if [ -d /etc/X11/wdm ]
    then
	logtoboth "> Plugin $pfx: Found Display Manager wdm"
	bbhandled=1
	if [ $nodmconsole -eq 1 ]
	then
	    logtoboth "> Plugin $pfx: Disable wdm on console"
	    sed -i "s/\:0 local \/usr\/bin\/X :0 vt7 -nolisten tcp/\#\:0 local \/usr\/bin\/X :0 vt7 -nolisten tcp/"  /etc/X11/wdm/Xservers
	    # RealVNC server operation with wdm unknown, so disable RealVNC 
	    [ -f /etc/sdm/0piboot/040-realvnc-server.sh ] && mv -f /etc/sdm/0piboot/040-realvnc-server.sh /etc/sdm/0piboot/.040-realvnc-server.sh
	    systemctl set-default multi-user.target
	    delaydmenable xdm B1
	else
	    delaydmenable wdm B3
	fi
    fi
    #
    # If Lite and no known display manager found set to console no login
    #
    if [ ! -d /etc/lightdm -a $bbhandled -eq 0 ]
    then
	# Lite with no known Desktop
	if [ $reboot -eq 1 ]
	then
	    logtoboth "> Plugin $pfx: No sdm-configurable Display Manager found"
	    logtoboth "> Plugin $pfx: Set RasPiOS to B1:'console no login' for sdm FirstBoot"
	    #SUDO_USER="$userx" raspi-config do_boot_behaviour B1 nonint > /dev/null 2>&1
	    do_raspiconfig do_boot_behaviour B1
	    if (grep '^boot_behav' /etc/sdm/1piboot.conf > /dev/null 2>&1) || [[ "$(cat /etc/sdm/assets/gfxbbh 2>/dev/null)" != "" ]]
	    then
		aval=$(getfinalbbh B1)
		logtoboth "% Boot behavior setting '$aval' will be honored after sdm FirstBoot"
	    else
		[ $autologin -eq 1 ] && bbh="B2" || bbh="B1"
		[ "$bbh" != "B1" ] && logtoboth "% Console Autologin setting '$bbh' will be re-enabled after sdm FirstBoot"
		setdelayedbbh $bbh
	    fi
	fi
    fi
}

# $1 is the phase: "0", "1", or "post-install"
# $2 is the argument list: arg1=val1|arg2=val2|arg3=val3| ...
#
# Main code for the Plugin
#
phase=$1
pfx="$(basename $0)"     #For messages
args="$2"
loadparams
vldargs="|graphics|nodmconsole|nopiwiz|videomode|runfunction|runargs|"
rqdargs=""
assetdir="$SDMPT/etc/sdm/assets/graphics"

if [ "$phase" == "0" ]
then
    #
    # In Phase 0 all references to directories in the image must be preceded by $SDMPT
    #
    plugin_getargs $pfx "$args" "$vldargs" "$rqdargs" || exit
    plugin_printkeys
elif [ "$phase" == "1" ]
then
    #
    # Phase 1 (in nspawn)
    #
    logtoboth "* Plugin $pfx: Start Phase 1"
    #logfreespace "at start of Plugin $pfx Phase 1"
    plugin_getargs $pfx "$args" "$vldargs" "$rqdargs"
    case "${graphics,,}" in
	labwc)
	    [ "$(type -p labwc)" == "" ] && logtobothex "? Plugin $pfx: Labwc is not installed"
	    ;;
	wayfire)
	    [ "$(type -p wayfire)" == "" ] && logtobothex "? Plugin $pfx: wayfire is not installed"
	    ;;
	x11)
	    logtoboth "> Plugin $pfx: X11 requested"
	    if [ ! -x /bin/Xorg ]
	    then
		x11pkgs="xserver-xorg xserver-xorg-core xserver-common"
		logtoboth "> Plugin $pfx: Install Core X11 packages: $x11pkgs"
		doinstalls "$x11pkgs" "X11 Core Install"
	    fi
	    ;;
    esac
    #logfreespace "at end of $pfx Phase 1"
    logtoboth "* Plugin $pfx: Complete Phase 1"
elif [ "$phase" == "post-install" ]
then
    #
    # Plugin Post-install edits
    #
    logtoboth "* Plugin $pfx: Start Phase post-install"
    plugin_getargs $pfx "$args" "$vldargs" "$rqdargs"
    #logfreespace "at start of Plugin $pfx Phase post-install"
    [ -v nodmconsole ] && nodmconsole=1 || nodmconsole=0
    if [ "$videomode" != "" ]
    then
	logtoboth "> Add cmdline video mode 'video=$videomode' to /boot/cmdline.txt"
	[ -f /boot/cmdline.txt ] && sed -i "1 s/^/video=$videomode /" /boot/cmdline.txt
	[ -f /boot/firmware/cmdline.txt ] && sed -i "1 s/^/video=$videomode /" /boot/firmware/cmdline.txt
    fi
    if [ -v nopiwiz ]
    then
	logtoboth "> Plugin $pfx: Disable running piwiz and userconfig on first system boot"
	[ -f /etc/xdg/autostart/piwiz.desktop ] && mv /etc/xdg/autostart/piwiz.desktop /etc/xdg/autostart/.piwiz.desktop.sdm
	systemctl disable userconfig.service > /dev/null 2>&1
	systemctl mask    userconfig.service > /dev/null 2>&1
	getent passwd rpi-first-boot-wizard > /dev/null && userdel -r rpi-first-boot-wizard > /dev/null 2>&1
	[ -f /etc/systemd/system/getty@tty1.service.d/autologin.conf ] && mv /etc/systemd/system/getty@tty1.service.d/autologin.conf /etc/systemd/system/getty@tty1.service.d/.autologin.conf.sdm
	rm -f /etc/sudoers.d/010_wiz-nopasswd
	rm -f /etc/xdg/autostart/deluser.desktop
    fi
    case "${graphics,,}" in
	labwc)
	    case "$raspiosver" in
		12) logtoboth "> Plugin $pfx: Set Graphics mode to Wayland Labwc"
		    do_raspiconfig do_wayland W3
		    ;;
		*) logtobothex "? Plugin $pfx: sdm does not support Labwc pre-Bookworm"
		   ;;
	    esac
	    ;;
	wayfire|wayland)
	    case "$raspiosver" in
		12) logtoboth "> Plugin $pfx: Set Graphics mode to Wayland Wayfire"
		    do_raspiconfig do_wayland W2
		    ;;
		*) logtobothex "? n Plugin $pfx: sdm does not support Wayfire pre-Bookworm"
		   ;;
	    esac
	    ;;
	x11)
	    case "$raspiosver" in
		12) if [ -f /etc/lightdm/lightdm.conf ]
		    then
			logtoboth "> Plugin $pfx: Set Graphics mode to X11"
			do_raspiconfig do_wayland W1
		    fi
		    ;;
		# X11 is default on RasPiOS 11 and earlier
		* ) logtoboth "% Plugin $pfx: X11 is default on pre-Bookworm"
		    ;;
	    esac
    esac
    gfxcfgpostinstall
elif [ "$phase" == "runfunction" ]
then
    plugin_getargs $pfx "$args" "$vldargs" "$rqdargs"
    plugin_printkeys
    [ -v nodmconsole ] && nodmconsole=1 || nodmconsole=0
    if [ "$runfunction" != "" ]
    then
	logtoboth "> Plugin $pfx: Run function: $runfunction $runargs"
	$runfunction $runargs
    else
	logtoboth "? Plugin $pfx: Run function called with no function"
    fi
fi
