#!/bin/sh -e
#
# tmux-ps - switch to tmux window which hosts tty that is controlling process
# matching <pattern>
#
# usage: tmux-ps <pattern>

window_with_tty() {
  tmux list-panes -a -F '#{pane_tty} #{session_name}:#{window_index}' \
    | grep "$1" | sort -u | head -1 | awk '{ print $2 }'
}

# shellcheck disable=SC2009
ps -o 'tty=,pid=,ppid=,command=' | grep "$1" | grep -wv grep | grep -wv $$ \
  | while read -r tty pid ppid command; do
    window_id="$(window_with_tty "${tty}")"
    tmux select-window -t "${window_id}"
    tmux switch-client -t "${window_id%:*}"
    break
  done
