if [ -z "$TMUX" ]; then
    # If we're in SSH
    if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then
        echo "Welcome via SSH..."
    # If we're in a TTY without X
    elif [ -z "$DISPLAY" ]; then
        # Optional X start code commented out
        # echo "Start X? ..."
        # startx
    # Regular terminal with no tmux
    else
        tmux_sessions=$(tmux ls 2>/dev/null)
        tmux_status=$?
        if [ $tmux_status -ne 0 ]; then
            echo "Press any key to cancel tmux autostart..."
            read -t 0.7 -n 1 -s -r
            if [ $? -ne 0 ]; then
                tmux new -s default
            fi
        else
            tmux attach -t default || tmux new -s default
        fi
    fi
fi

function tmuxLauncher {
    local selected_dir full_path session_name

    selected_dir=$(fd --base-directory ~/Dev --search-path . -t d -d 2 | fzf)
    [[ -z "$selected_dir" ]] && { zle reset-prompt; return }

    selected_dir="${selected_dir#./}"
    selected_dir="${selected_dir%/}"
    full_path="$HOME/Dev/$selected_dir"

    session_name="${selected_dir//\//-}"
    session_name="${session_name%-}"

    if [[ -n "$TMUX" ]]; then
        tmux new-window -n "$session_name" -c "$full_path"
        zle reset-prompt
    else
        echo "tmux new-session -s '$session_name' -c '$full_path'" > /tmp/tmux_cmd
        zle accept-line
        BUFFER="source /tmp/tmux_cmd && rm /tmp/tmux_cmd"
        zle accept-line
    fi
}

zle -N tmuxLauncher
bindkey "^t" tmuxLauncher

