summaryrefslogtreecommitdiffstatshomepage
path: root/tmux/.local/bin/tmux-sshr
blob: 11186fff5d0492dceed4979f2b85f19975603cad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/bin/sh

HOST=$(tmux display -p '#h' 2>/dev/null)

if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then
	tmux -L ssh run-shell "tmux-sshr"
	exit 0
fi

if [ "$#" -eq 0 ]; then
	ATTACHED=$(tmux display -p '#{?#{m:*ssh,#{socket_path}},#S,#{host}}' 2>/dev/null)

	set -- "$(
		sshr --all --exclude="$ATTACHED" |
			fzf-tmux -p20%,20% -- --print-query --tac |
			tail -1
	)"
fi

if [ -z "$1" ]; then
	exit 0
fi

target="$1"

if [ "$target" = "$HOST" ]; then
	tmux detach -E 'tmux new -A'
else
	if ! tmux -L ssh has-session -t "$target"; then
		tmux_local_sock=$(tmux -L ssh start-server \; display -p "#{socket_path}")
		tmux_remote_sock=$(
			ssh -T \
				-o "ControlMaster=auto" \
				-o "ControlPath=${XDG_RUNTIME_DIR}/ssh.%C" \
				"$target" 'tmux -L ssh start-server \; display -p "#{socket_path}"'
		)

		if [ -z "$tmux_local_sock" ] || [ -z "$tmux_remote_sock" ]; then
			exit 1
		fi

		tmux -L ssh new-session -ds "$target" \
			ssh -t \
			-o "ControlMaster=auto" \
			-o "ControlPath=${XDG_RUNTIME_DIR}/ssh.%C" \
			-R "2222:localhost:22" \
			-R "${XDG_RUNTIME_DIR}/xdg-open.socket:${XDG_RUNTIME_DIR}/xdg-open.socket" \
			-R "$tmux_remote_sock:$tmux_local_sock" \
			"$target" "zsh -l -c 'tmux new -A'"
	fi

	if [ -z "$TMUX" ]; then
		tmux -L ssh attach -t "$target"
	else
		tmux detach -E "tmux -L ssh attach -t $target"
	fi

	exit 0
fi