#!/bin/sh
#
# livesys-hyprland: hyprland specific setup for livesys
# SPDX-License-Identifier: GPL-3.0-or-later
#

HYPRLAND_SESSION_FILE="hyprland.desktop"

# set up autologin for user liveuser
# Support greetd, GDM, and SDDM

if [ -f /etc/greetd/config.toml ]; then
    # greetd (common for Hyprland setups)
    cat > /etc/greetd/config.toml << GREETD_EOF
[terminal]
vt = 1

[default_session]
command = "Hyprland"
user = "liveuser"
GREETD_EOF

elif [ -f /etc/gdm/custom.conf ]; then
    # GDM
    sed -i 's/^\[daemon\]/[daemon]\nAutomaticLoginEnable=True\nAutomaticLogin=liveuser/' /etc/gdm/custom.conf
    # Set default session for GDM
    mkdir -p /var/lib/AccountsService/users
    cat > /var/lib/AccountsService/users/liveuser << GDM_USER_EOF
[User]
Session=${HYPRLAND_SESSION_FILE}
XSession=${HYPRLAND_SESSION_FILE}
SystemAccount=false
GDM_USER_EOF

elif [ -f /etc/sddm.conf ]; then
    # SDDM (existing config)
    sed -i 's/^#User=.*/User=liveuser/' /etc/sddm.conf
    sed -i "s/^#Session=.*/Session=${HYPRLAND_SESSION_FILE}/" /etc/sddm.conf

else
    # SDDM (create new config)
    cat > /etc/sddm.conf << SDDM_EOF
[Autologin]
User=liveuser
Session=${HYPRLAND_SESSION_FILE}
SDDM_EOF
fi

# Show harddisk install on the desktop
if [ -f /usr/share/applications/liveinst.desktop ]; then
    sed -i -e 's/NoDisplay=true/NoDisplay=false/' /usr/share/applications/liveinst.desktop
fi
mkdir -p /home/liveuser/Desktop

# echoing type liveinst to start the installer
echo "echo 'Please type liveinst and press Enter to start the installer'" >> /home/liveuser/.bashrc

# Copy hyprland configuration files for live environment
# Using cp instead of symlinks for reliability across filesystems and SELinux contexts
if [ -d /usr/share/hypr/config.live.d ]; then
    mkdir -p /home/liveuser/.config/hypr/
    cp /usr/share/hypr/config.live.d/* /home/liveuser/.config/hypr/
    chown -R liveuser:liveuser /home/liveuser/.config/hypr/
fi
