#!/usr/bin/env sh
#
# tat - attach or create tmux session named after current directory
#
# Usage: tat [session_name]
#
# Arguments:
#   session_name - Custom session name (default: current directory name)
#
# Examples:
#   tat              # Create/attach session named after current dir
#   tat myproject    # Create/attach session named "myproject"
#   tat work-stuff   # Create/attach session named "work-stuff"
#
# Returns: Attaches to tmux session, creating it if it doesn't exist
# Behavior:
#   - If not in tmux: creates new session or attaches to existing
#   - If in tmux: switches to target session, creating if needed
#   - Session name: current directory basename with dots converted to dashes
#
# one-liner: `tat() { tmux attach -t "$1" || tmux new -s "$1"; }`
#
# ---
# source: https://github.com/joshukraine/dotfiles

path_name="$(basename "${PWD}" | tr -d '.')"
session_name=${1-${path_name}}

not_in_tmux() {
  [ -z "${TMUX}" ]
}

session_exists() {
  tmux list-sessions | sed -E 's/:.*$//' | grep -q "^${session_name}$"
}

create_detached_session() {
  (TMUX='' tmux new-session -Ad -s "${session_name}")
}

create_if_needed_and_attach() {
  if not_in_tmux; then
    tmux new-session -As "${session_name}"
  else
    if ! session_exists; then
      create_detached_session
    fi
    tmux switch-client -t "${session_name}"
  fi
}
create_if_needed_and_attach
