#!/bin/zsh

if ! tmux has-session -t td-cli 2>/dev/null; then
  tmux setenv -g TD_TASK_DIR ~/git/tasks/
  tmux new-session -d -s td-cli ~/installs/scripts/td
fi

if [[ "$(tmux display-message -p -F "#{session_name}")" == "td-cli" ]]; then
  tmux detach-client
  tmux display-popup -C
  osascript <<EOF
tell application "System Events"
    set frontApp to name of first application process whose frontmost is true
end tell

if frontApp is "Terminal" then
    tell application "Terminal"
        activate
        delay 0.3
        tell application "System Events"
            keystroke "x" using control down  -- Send Ctrl + x (tmux prefix)
            delay 0.3
            keystroke ":kill-session"
            delay 0.3
            key code 36  -- Press Enter to execute :detach
            delay 0.3
            keystroke "exit"
            key code 36  -- Press Enter to execute exit
        end tell
    end tell
end if
EOF
  osascript -e 'tell application "Terminal" to quit'
else
  tmux display-popup -d -C -E -w90% -h90% 'tmux attach-session -x -f wait-exit -t td-cli'
fi
