summaryrefslogtreecommitdiff
path: root/bin/ssh-and-tmux
blob: 87ace865dd82962518c3568c84a2b77437a72118 (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
#!/bin/bash

# when mosh isn't installed on the server, but tmux is, use this to get a
# fairly persistent set of remote shell sessions.  I used to use autossh here,
# but that means surprise dialogs asking to authorise use of an SSH key;
# instead, just hit <Ret> to restart a window's connection when it's
# convenient
#
# (The reason that I get prompted is because I have a short
# ServerAliveInterval and low ServerAliveCountMax, but that's desirable,
# because unresponsive SSH sessions are a massive pain)

getopt=$(getopt -s bash -o "" -l 'container-cmd:,container-name:' -n ssh-and-tmux -- "$@")
eval "set - $getopt"

while true; do
    case "$1" in
	'--container-cmd') container_cmd=$2; shift 2; continue ;;
	'--container-name') container_name=$2; shift 2; continue ;;

	'--') shift; break ;;
    esac
done

host="$1"
session="${2:-default}"
cmd="tmux new-session -A -c \$HOME -s $session"
if [ -n "$container_name" ]; then
    display_host="$container_name"
    cmd="$(printf "$container_cmd" "$container_name") -- $cmd"
else
    display_host="$host"
fi
echo -ne "\033]0;tmux $session on $display_host\007"
prompt="Press any key to reconnect to tmux session $session on $display_host; d/C-d/C-c to give up .."

while true; do
    ssh -t "$host" "$cmd"
    clear
    read -n 1 -r -s -p "$prompt" ch
    [ "$ch" = $'\04' -o "$ch" = d ] && echo && exit
done