#!/usr/bin/env sh

# vimrc
# -----
# function! s:moveToPane(direction)
#   let oldnr = winnr()
#   execute 'wincmd ' . a:direction
#   if oldnr == winnr()
#     call system('~/.config/tmux/scripts/select-pane ' . a:direction)
#   endif
# endfunction
#
# command! MoveToLeft call s:moveToPane('h')
# command! MoveToDown call s:moveToPane('j')
# command! MoveToUp call s:moveToPane('k')
# command! MoveToRight call s:moveToPane('l')
# nnoremap <silent> <C-h> :MoveToLeft<cr>
# nnoremap <silent> <C-j> :MoveToDown<cr>
# nnoremap <silent> <C-k> :MoveToUp<cr>
# nnoremap <silent> <C-l> :MoveToRight<cr>

# tmux.conf
# ---------
# # smart pane switching with awareness of vim splits
# unbind Up
# unbind Down
# unbind Left
# unbind Right
# is_vim='echo "#{pane_current_command}" | grep -iqE "(^|\/)g?(view|n?vim?x?)(diff)?$"'
# bind -n C-h if-shell "$is_vim" "send-keys C-h" "run '~/.config/tmux/scripts/select-pane L'"
# bind -n C-j if-shell "$is_vim" "send-keys C-j" "run '~/.config/tmux/scripts/select-pane D'"
# bind -n C-k if-shell "$is_vim" "send-keys C-k" "run '~/.config/tmux/scripts/select-pane U'"
# bind -n C-l if-shell "$is_vim" "send-keys C-l" "run '~/.config/tmux/scripts/select-pane R'"
# bind -T copy-mode-vi C-h if-shell "$is_vim" "send-keys C-h" "run '~/.config/tmux/scripts/select-pane L'"
# bind -T copy-mode-vi C-j if-shell "$is_vim" "send-keys C-j" "run '~/.config/tmux/scripts/select-pane D'"
# bind -T copy-mode-vi C-k if-shell "$is_vim" "send-keys C-k" "run '~/.config/tmux/scripts/select-pane U'"
# bind -T copy-mode-vi C-l if-shell "$is_vim" "send-keys C-l" "run '~/.config/tmux/scripts/select-pane R'"

if [ -z "${TMUX}" ]; then
  exit 1
fi

# see: https://github.com/dalejung/tmux-select-pane-no-wrap

direction="$1"

case "${direction}" in
  k | U)
    coord='top'
    op='gt'
    sort_flags='n'
    direction='U'
    ;;
  j | D)
    coord='bottom'
    op='lt'
    sort_flags='nr'
    direction='D'
    ;;
  h | L)
    coord='left'
    op='gt'
    sort_flags='n'
    direction='L'
    ;;
  l | R)
    coord='right'
    op='lt'
    sort_flags='nr'
    direction='R'
    ;;
  *)
    printf '%s\n' "Unknown direction: ${direction}" >&2
    exit 1
    ;;
esac

cmd="#{pane_id}:#{pane_${coord}}:#{?pane_active,_active_,_no_}"
panes=$(tmux list-panes -F "${cmd}")
active_pane=$(echo "${panes}" | grep _active_)
active_pane_id=$(echo "${active_pane}" | cut -d: -f1)
active_coord=$(echo "${active_pane}" | cut -d: -f2)
coords=$(echo "${panes}" | cut -d: -f2)
test_coord=$(echo "${coords}" | sort -"${sort_flags}" | head -n 1)

case ${op} in
  lt)
    if [ "${active_coord}" -lt "${test_coord}" ]; then
      tmux select-pane -"${direction}"
    fi
    ;;
  gt)
    if [ "${active_coord}" -gt "${test_coord}" ]; then
      tmux select-pane -"${direction}"
    fi
    ;;
  *)
    exit 1
    ;;
esac
