aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/tmux/.local/bin/tmux-sshr
blob: c761a15bdd9dd84c6c399d70017c7b4bfe763f5b (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
#!/bin/sh

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

if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then
	tmux_sock=$(tmux display -p "#{socket_path}")
	tmux -S "${tmux_sock}.control" run-shell "tmux-sshr"
	exit 0
fi

if [ "$#" -eq 0 ]; then
	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_sock=$(tmux -L ssh start-server \; display -p "#{socket_path}")
		runtime=$(
			ssh -T \
				-o "ControlMaster=auto" \
				-o "ControlPath=${XDG_RUNTIME_DIR}/ssh.%C" \
				"$target" \
				'printf "%s\n" "$XDG_RUNTIME_DIR"'
		)

		tmux -L ssh new-session -ds "$target" \
			ssh -t \
			-o "ControlMaster=auto" \
			-o "ControlPath=${XDG_RUNTIME_DIR}/ssh.%C" \
			-R "2222:localhost:22" \
			-R "${runtime}/xdg-open.socket:${XDG_RUNTIME_DIR}/xdg-open.socket" \
			-R "${runtime}/tmux.${HOST}.control:${tmux_sock}" \
			"$target" "zsh -l -c 'tmux -S \${XDG_RUNTIME_DIR}/tmux.${HOST} 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