#!/bin/sh -e
# Usage: tmux-goto-pane-id [target_pane_id]
#        tmux-goto-pane-id %42

echo_err() {
  printf '%s\n' "$*" >&2
}

die_run() {
  "$@"
  exit 1
}

if [ "$#" = 0 ]; then
  # awk 'NR == 1 { next } /^$/ { exit } { print substr($0, 3) }' "$0"
  grep "^#/" "$0" | cut -c4-
  exit 1
fi

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  awk 'NR == 1 { next } /^$/ { exit } { print substr($0, 3) }' "$0"
  grep "^# " "$0" | cut -c3-
  exit 0
fi

TARGET_PANE_ID="$1"

SESSION_NAME=$(tmux list-panes -t "${TARGET_PANE_ID}" -F "#{session_name}")
WINDOW_ID=$(tmux list-panes -t "${TARGET_PANE_ID}" -F "#{window_id}")
PANE_INDEX=$(tmux list-panes -t "${TARGET_PANE_ID}" -F "#{pane_index}")

tmux switch-client -t "${SESSION_NAME}" \
  || die_run tmux display-message "Cannot switch to session '${SESSION_NAME}'"
tmux select-window -t "${WINDOW_ID}" \
  || die_run tmux display-message "Cannot switch to window id '${WINDOW_ID}'"
tmux select-pane -t "${PANE_INDEX}" \
  || die_run tmux display-message "Cannot switch to pane index '${PANE_INDEX}'"
