#!/bin/bash

# Install and configure UWSM (Universal Wayland Session Manager) for Hyprland

# Install UWSM and dbus-broker (recommended)
yay -S --noconfirm --needed uwsm dbus-broker

# Enable and start dbus-broker
sudo systemctl enable dbus-broker.service
sudo systemctl --global enable dbus-broker.service

# Create uwsm config directory
mkdir -p ~/.config/uwsm

# Create common environment variables file
cat > ~/.config/uwsm/env << 'EOF'
# Common environment variables for all graphical sessions
export GTK_THEME=Adwaita:dark
export QT_STYLE_OVERRIDE=Adwaita-Dark
export XCURSOR_THEME=Yaru
export XCURSOR_SIZE=24
export MOZ_ENABLE_WAYLAND=1
export QT_QPA_PLATFORM=wayland
export SDL_VIDEODRIVER=wayland
export _JAVA_AWT_WM_NONREPARENTING=1
export XDG_CURRENT_DESKTOP=Hyprland
export XDG_SESSION_TYPE=wayland
export XDG_SESSION_DESKTOP=Hyprland
EOF

# Create Hyprland-specific environment variables file
cat > ~/.config/uwsm/env-hyprland << 'EOF'
# Hyprland-specific environment variables
export HYPRLAND_LOG_WLR=1
export HYPRLAND_NO_RT=1
EOF

# Create desktop entry for display manager
sudo mkdir -p /usr/share/wayland-sessions
sudo tee /usr/share/wayland-sessions/hyprland-uwsm.desktop > /dev/null << 'EOF'
[Desktop Entry]
Name=Hyprland (with UWSM)
Comment=Hyprland managed by Universal Wayland Session Manager
Exec=uwsm start hyprland.desktop
Type=Application
DesktopNames=Hyprland
EOF

# Add UWSM startup to .profile if not already present
if ! grep -q "uwsm check may-start" ~/.profile 2>/dev/null; then
    echo "Adding UWSM startup to ~/.profile"
    cat >> ~/.profile << 'EOF'

# Start UWSM if conditions are met
if uwsm check may-start && uwsm select; then
  exec uwsm start default
fi
EOF
fi

# Create a UWSM service to handle Hyprland autostart applications
mkdir -p ~/.config/systemd/user
cat > ~/.config/systemd/user/uwsm-app-daemon.service << 'EOF'
[Unit]
Description=UWSM Application Daemon
PartOf=graphical-session.target
After=graphical-session.target

[Service]
Type=forking
ExecStart=/bin/bash -c 'uwsm finalize'
RemainAfterExit=yes

[Install]
WantedBy=graphical-session.target
EOF

# Enable the UWSM service
systemctl --user enable uwsm-app-daemon.service

echo "UWSM installation and configuration completed!"
echo ""
echo "Usage:"
echo "  - From TTY: The system will automatically start UWSM when logging in"
echo "  - From display manager: Select 'Hyprland (with UWSM)' from the session menu"
echo "  - Launch applications: Use 'uwsm app -- command' instead of just 'command'"
echo "  - Stop session: Use 'uwsm stop' (do not use Hyprland's exit command)"
echo ""
echo "Note: Update your Hyprland config to use 'uwsm app --' for exec-once commands"
echo "Example: exec-once = uwsm app -- waybar"