#!/bin/bash
#===============================================================================
# Script Name: startkde-biglinux
# Description: KDE Plasma session initialization for BigLinux
#              Handles first login configuration, environment setup,
#              GPU optimizations, and theme application.
# Package:     biglinux-session-and-themes
#
# Dependencies:
#   - plasma-workspace (startplasma-x11/wayland)
#   - vulkaninfo (GPU detection)
#   - kwriteconfig6 (KDE configuration)
#   - big-theme-plasma, big-theme-apps (theme management)
#===============================================================================

# Check for hardware Vulkan support (not just llvmpipe software renderer)
if vulkaninfo --summary 2>/dev/null | grep 'deviceName' | grep -vq 'llvmpipe'; then
    unset QSG_RENDER_LOOP
    [[ -z $Vulkan_Supported ]] && export Vulkan_Supported=1
else
    # Software rendering: Use cairo for mesa-amber or virtual machines
    if compgen -G /var/lib/pacman/local/mesa-amber-* || systemd-detect-virt -q; then
        [[ -z $GSK_RENDERER ]] && export GSK_RENDERER="cairo"
    else
        [[ -z $GSK_RENDERER ]] && export GSK_RENDERER="gl"
    fi
fi

# Enable animations in virtualized mode
[[ -z $KWIN_EFFECTS_FORCE_ANIMATIONS ]] && export KWIN_EFFECTS_FORCE_ANIMATIONS=1

#-------------------------------------------------------------------------------
# Session-specific Configuration
#-------------------------------------------------------------------------------
if [[ "$1" == "wayland" ]]; then
    # Reduce input lag for keyboard input methods
    [[ -z $IBUS_ENABLE_SYNC_MODE ]] && export IBUS_ENABLE_SYNC_MODE=1

    exec --no-startup-id /usr/lib/pam_kwallet_init

else
    # X11-specific configuration
    RESOLUTION="$(xdpyinfo | awk '/dimensions/ {print $2}')"
    SCREEN="$(xrandr | grep 'connected primary' | cut -f1 -d" ")"
    WIDTH=${RESOLUTION//x*}
    HEIGHT=${RESOLUTION//*x}

    [[ -z $MOZ_USE_XINPUT2 ]] && export MOZ_USE_XINPUT2=1
fi

# Ensure LANGUAGE is set
[[ -z $LANGUAGE ]] && export LANGUAGE=$LANG

#-------------------------------------------------------------------------------
# First Login: Shell Configuration
#-------------------------------------------------------------------------------
if [[ ! -f "$HOME/.biglinux-shell-changed" ]]; then
    biglinux-change-default-shell bash-power
    : > "$HOME/.biglinux-shell-changed"
fi

# Enable KDE file dialog in GTK apps
[[ -z $GTK_USE_PORTAL ]] && export GTK_USE_PORTAL=1

#-------------------------------------------------------------------------------
# Keyboard LED Control
#-------------------------------------------------------------------------------
if [[ -e "$HOME/.config/ledkeyboard" ]]; then
    big-keyboard-led on
fi

#-------------------------------------------------------------------------------
# First Login: Theme and JamesDSP Configuration
#-------------------------------------------------------------------------------
themeFile="/etc/big-default-config/theme"
if [[ -e "$themeFile" && ! -e "$HOME/.big_desktop_theme" ]]; then
    # Apply theme from LiveCD selection
    big-theme-apps --apply "$(<"$themeFile")"
    systemctl --user enable big-welcome

    # Configure JamesDSP audio enhancement
    if [[ -e /etc/big-default-config/jamesdsp && -e "$HOME/.config/jamesdsp/application.conf" ]]; then
        sed -i "s|AutoStartEnabled=false|AutoStartEnabled=true|g" "$HOME/.config/jamesdsp/application.conf"
    else
        sed -i "s|AutoStartEnabled=true|AutoStartEnabled=false|g" "$HOME/.config/jamesdsp/application.conf"
    fi
fi

# Sync GTK theme with current settings if theme file doesn't exist
if [[ ! -e "$themeFile" && -e "$HOME/.big_desktop_theme" ]]; then
    dconf write /org/gnome/desktop/interface/gtk-theme "'$(grep 'gtk-theme-name=' "$HOME/.config/gtk-3.0/settings.ini" | cut -f2-5 -d=)'"
fi

#-------------------------------------------------------------------------------
# First Login: Desktop Layout Configuration
#-------------------------------------------------------------------------------
desktopFile="/etc/big-default-config/desktop"
if [[ ! -e "$HOME/.kdebiglinux/lastlogin" && -e "$desktopFile" ]]; then
    big-theme-plasma --apply $(cut -f2 -d" " "$desktopFile") quiet
fi

#-------------------------------------------------------------------------------
# KSplash: Link Current Wallpaper for Boot Splash
#-------------------------------------------------------------------------------
# Get containment ID of current wallpaper
wallpaperId=${ grep -m1 -Eo '\[Containments\]\[[0-9]{1,5}\]\[Wallpaper\]\[org.kde.image\]' ~/.config/plasma-org.kde.plasma.desktop-appletsrc | awk -F '\\[|\\]' '{print $4}'; }

# Get wallpaper path from KDE config
plasmaWallpaper=${ kreadconfig6 --file ~/.config/plasma-org.kde.plasma.desktop-appletsrc --group Containments --group $wallpaperId --group Wallpaper --group org.kde.image --group General --key Image; }

# Create symlink for ksplash (remove file:// prefix if present)
ln -sf "${plasmaWallpaper#file://}" /tmp/bigksplash.jpg
chmod 777 /tmp/bigksplash.jpg

#-------------------------------------------------------------------------------
# Global Menu: Fix fullscreen when switching desktop layouts
#-------------------------------------------------------------------------------
nowlogin=$(<"$HOME/.kdebiglinux/lastused")
lastlogin=$(<"$HOME/.kdebiglinux/lastlogin")

if [[ "$nowlogin" != "$lastlogin" ]]; then
    big-theme-globalmenu
fi

echo "$nowlogin" > "$HOME/.kdebiglinux/lastlogin"

#-------------------------------------------------------------------------------
# Low Disk Space Warning Configuration
#-------------------------------------------------------------------------------
if [[ ! -e "$HOME/.config/freespacenotifierrc" && ! -e /livefs-pkgs.txt ]]; then
    echo '[General]
minimumSpace=5000' > "$HOME/.config/freespacenotifierrc"
fi

export XDG_SESSION_DESKTOP=KDE

# Enable SSH agent for key management
eval "$(ssh-agent -s)"

# Verify KDE portal in background
portal-kde-verify.sh &

# Restore laptop backlight level
sudo biglinux-backlight-restore 2>/dev/null &

#-------------------------------------------------------------------------------
# Fcitx Input Method Setup for Wayland
# Fixes accent/special character input problems in GTK apps
#-------------------------------------------------------------------------------
if [[ ! -e ~/.config/big_enabled_fcitx || -e /livefs-pkgs.txt ]] && \
   [[ "$1" == "wayland" && -e /usr/share/applications/fcitx5-wayland-launcher.desktop ]] && \
   ! grep -q 'InputMethod\[$e\]=' "$HOME/.config/kwinrc"; then
    # Mark as enabled to only run once
    : > ~/.config/big_enabled_fcitx

    # Add InputMethod config (without [$e] due to kwriteconfig6 limitation)
    kwriteconfig6 --group "Wayland" --key 'InputMethod$e' --file "$HOME/.config/kwinrc" "/usr/share/applications/fcitx5-wayland-launcher.desktop"

    # Fix the key format: InputMethod$e -> InputMethod[$e]
    sed -i 's|InputMethod$e|InputMethod[$e]|g' "$HOME/.config/kwinrc"
fi

#-------------------------------------------------------------------------------
# Klassy fix theme after update to 6.5 or more recently version
#-------------------------------------------------------------------------------
if [[ ! -e "$HOME/.config/klassy/klassy-verify-update" ]]; then
    cp -f /usr/share/biglinux/themes/biglinux/.config/klassy/klassyrc "$HOME/.config/klassy/klassyrc"
    cp -f /usr/share/biglinux/themes/biglinux/.config/klassy/windecopresetsrc "$HOME/.config/klassy/windecopresetsrc"
    > "$HOME/.config/klassy/klassy-verify-update"
fi

#-------------------------------------------------------------------------------
# Start Plasma Session
#-------------------------------------------------------------------------------
exec startplasma-$XDG_SESSION_TYPE
