#! /usr/bin/env bash

# For some details on how this code got to be:
# https://emacs.stackexchange.com/a/72377/38372

###
### edit-with-spacemacs, ensures a daemon named spacemacs is working
### if it's not running, it will launch the daemon
### Then it will check if a frame already exists, if it does, it will
### open the file in that frame.
### If a frame doesn't exist, a new frame will open.
### Note that if that frame is in another virtual desktop, you will
### need to manually switch there.
###

MY_EMACS_PROFILE=${CHEMACS_PROFILE:-spacemacs}
MY_SILENT=${MY_SILENT:-"/dev/null"}
MY_EMACS_CREATEFRAME="--create-frame"
MY_EMACS_NO_WAIT="--no-wait"
DEBUG_MY_EMACS=${DEBUG_MY_EMACS}
_cli="/usr/bin/emacsclient --socket-name=$MY_EMACS_PROFILE "

# MY_SILENT="/dev/tty"
# MY_EMACS_NO_WAIT=""

if [ "$DISPLAY" = "" ]; then
  MY_EMACS_NO_WAIT=""
fi

# set | grep '^MY_EMACS' 1>&2

function q_()  { printf  "'%s'\n"  "${@}"; }

function prep_path() {
  local _cli_path="$(q_ "${@}")"
  _cli_path="${_cli_path// /\\ }"
  _cli_path=$(printf "$_cli_path")

  printf $_cli_path
}

2>$MY_SILENT $_cli --eval '(+ 1 0)' > /dev/null || {
  echo "Starting server..."
  2>$MY_SILENT /usr/bin/emacs --bg-daemon=$MY_EMACS_PROFILE -- --with-profile=spacemacs
}
# At this point the server should be up and running, and so now we just
# need to see if we have any frames open
# If there are frames, we are NOT going to create a new frame, and so
# MY_EMACS_CREATEFRAME will be set to blank.
[ "$($_cli --eval '(> (length (frame-list)) 1)')" == "t" ] && MY_EMACS_CREATEFRAME=''

client_args=$(prep_path "${@}")
[ "$client_args" == "''" ] && client_args='--eval "(select-frame-set-input-focus (selected-frame)) (make-frame-visible (selected-frame)) (raise-frame)"'
eval "$_cli $MY_EMACS_CREATEFRAME $MY_EMACS_NO_WAIT $client_args"