#!/usr/bin/env sh
#
# tmls - fuzzy list tmux sessions and switch
# for use in tmux.conf: bind \` display-popup -h 20 -w 32 -E "tmls"
#
# dependencies: fzf

ensure() {
  if ! command -v "$1" >/dev/null 2>&1; then
    printf "%s not found. Make sure you have it installed.\n" "$1"
    exit 1
  fi
}

filter() {
  height=""
  if [ "$2" != "" ]; then
    height="${height}--height $2"
  fi
  # shellcheck disable=SC2086
  tmux list-sessions -F "#S" | fzf --header "$1" ${height} --select-1 --exit-0
}

ensure tmux
ensure fzf

if ! tmux ls >/dev/null 2>&1; then
  printf "no sessions\n"
  exit 1
fi

if [ "${TMUX-}" != "" ]; then
  # shellcheck disable=SC2312
  tmux switch-client -t "$(filter "switch session")"
else
  # shellcheck disable=SC2312
  tmux attach-session -t "$(filter "attach session" 12)"
fi
