aboutsummaryrefslogtreecommitdiff
path: root/shell
blob: 0dd64e66abc00ed49e617602123026ee7b517972 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/bin/bash
#
# Simple $AUTOSSH and terminal multiplexer wrapper.
#

# Parameters
#
# We're enforcing a random monitoring por for autossh
# as some systems might deny reading /proc/net/tcp like
# kernels with grsecurity patch.
BASENAME="`basename $0`"
DEST="$1"
COMMAND="$2"
#LOCAL_MULTIPLEXER="wscreen"
LOCAL_MULTIPLEXER="wtmux"
MONITORING="-M $(($RANDOM + 1024))"
AUTOSSH="autossh $MONITORING"

# Set window title
# http://stackoverflow.com/questions/899609/gnu-screen-run-script-that-sends-commands-to-the-screen-session-it-is-being-run
function window_title {
  if [ -n "$STY" ]; then
    screen -p $WINDOW -X title "$*"
  elif [ -n "$TMUX" ]; then
    tmux rename-window "$*"
  else
    if which xtitle &> /dev/null; then
      xtitle -q "$*"
    fi
  fi
}

# Check if a named session exists, screen version
function shell_wscreen_ls {
  screen -ls $1 | grep -q "There is a screen on"
}

# Check if a named session exists, tmux version
function shell_wtmux_ls {
  tmux ls 2> /dev/null | grep -q ^$1:
}

# Try tmux, then screen
function shell_remote_multiplexer {
  tmux="tmux attach"

  if [ ! -z "$1" ]; then
    tmux="$tmux -t $1"
  fi

  echo "$SUDO $tmux || $SUDO screen -x $1"
}

# Syntax check
if [ -z "$DEST" ]; then
  exit 1
fi

# Set default screen title
window_title $DEST

# Dispatcher
if [ "$BASENAME" == "shells" ]; then
  # Remote screen shell using $AUTOSSH
  if [ "$COMMAND" == "root" ]; then
    SUDO="sudo"
    $AUTOSSH $DEST -t -- "`shell_remote_multiplexer`"
  else
    $AUTOSSH $DEST -t -- "`shell_remote_multiplexer` $COMMAND"
  fi
else
  if [ -z "$COMMAND" ] && shell_${LOCAL_MULTIPLEXER}_ls $DEST; then
    # Local existing screen shell
    $LOCAL_MULTIPLEXER $DEST
  elif [ -z "$COMMAND" ] && [ "$DEST" == "root" ]; then
    # Local root shell
    window_title root
    SUDO="sudo"
    eval `shell_remote_multiplexer`
  elif [ -z "$COMMAND" ] && ( [ -f "$HOME/.screen/$DEST" ] || [ -f "$HOME/.tmux/$DEST" ] ); then
    # Local root shell
    window_title $DEST
    shell local $DEST
  elif [ "$DEST" == "local" ]; then
    # Local screen shell
    window_title $COMMAND
    $LOCAL_MULTIPLEXER $COMMAND
  else
    # Remote shell using $AUTOSSH
    $AUTOSSH $DEST -t -- $COMMAND
  fi
fi

# Restore screen title
window_title terminal