#!/usr/bin/env bash
#
# tmux-fzf-panes - list tmux panes with fzf

tmux_panes() {
  panes=$(tmux list-panes -s -F '#I:#P - #{pane_current_path} #{pane_current_command}')
  current_pane=$(tmux display-message -p '#I:#P')
  current_window=$(tmux display-message -p '#I')

  target=$(
    echo "${panes}" | grep -v "${current_pane}" | fzf-tmux -p -- +m --reverse
  ) \
    || return
  target_window=$(echo "${target}" | awk 'BEGIN{FS=":|-"} { print $1 }')
  target_pane=$(echo "${target}" | awk 'BEGIN{FS=":|-"} { print $2 }' | cut -c 1)

  if [ "${current_window}" -eq "${target_window}" ]; then
    tmux select-pane -t "${target_window}.${target_pane}"
  else
    tmux select-pane -t "${target_window}.${target_pane}" \
      && tmux select-window -t "${target_window}"
  fi
}

tmux_panes "$@"
