#!/bin/sh

hyprctl dispatch focuswindow emacs

# Check to see if an emacsclient is running
if [ $(pgrep -c emacsclient) -gt 0 ]; then
    echo hi
    
    if [ "$XDG_SESSION_TYPE" = "x11" ]; then
        echo X11
        emacsrg=$(wmctrl -lx | rg emacs.Emacs | rg -v org-agenda | awk '{print $1}')
        echo $emacsrg

        if [ -z $emacsrg ]; then
            exec emacsclient -c &
            exit
        else
            exec wmctrl -ia $emacsrg
            exit
        fi
    else
        if [ "$KDE_FULL_SESSION" = "true" ]; then
            exec /home/chris/bin/ww -f emacs
            exit
        else
            echo WAYLAND
            emacsrg=$(hyprctl clients |  rg "emacs:" | rg -v dired)
            echo $emacsrg

            emacswin=$(echo $emacsrg | sed 's/.*\: //')
            echo $emacswin

            exec hyprctl dispatch focuswindow "class:emacs"
            exit
        fi
    fi

else
    if [ $(pgrep -c emacs) -gt 0 ]; then
        exec emacsclient -c &
    else
        alacritty -e emacs --daemon
        exec emacsclient -c &
    fi
fi