#!/usr/bin/env bash
alias notify-send="notify-send -t 3000 -i \"../../stigmacs/emacs_icon.png\" "

# Check if Emacs is running as a daemon
DAEMON_PID=$(pgrep -f "emacs --daemon")
BACKGROUND_DAEMON_PID=$(pgrep -f "emacs --bg-daemon")
FOREGROUND_DAEMON_PID=$(pgrep -f "emacs --fg-daemon")

# Check if Emacs GUI is running
GUI_PID=$(pgrep -f "emacs")

# If Emacs is running and the daemon isn't, start the daemon
if [[ -z $BACKGROUND_DAEMON_PID && -z $DAEMON_PID && -z $FOREGROUND_DAEMON_PID  && -n $GUI_PID ]]; then
    # notify-send "Starting Emacs daemon"
    emacs --daemon 2&>/dev/null
# if the daemon is running, restart it
elif [[ -n $DAEMON_PID || -n $BACKGROUND_DAEMON_PID || -n $FOREGROUND_DAEMON_PID ]]; then
    # notify-send "Restarting Emacs daemon"
    kill $BACKGROUND_DAEMON_PID 2>/dev/null
    kill $DAEMON_PID 2>/dev/null
    kill $FOREGROUND_DAEMON_PID 2>/dev/null
    emacs --daemon 2&>/dev/null
fi
