#!/bin/bash
#
# ScreenCSSH - Screen-based cluster SSH
# Version: 1.0
# Author: Travis Estill (travisce.com)
# Copyright (c) 2013 Travis Estill
# License: Distributed under the Lesser General Public License
#   (LGPL) http://www.gnu.org/copyleft/lesser.html
#   This program is distributed in the hope that it will be useful
#   - WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

# Main ScreenCSSH script

function rmtmpfiles {
  /bin/rm -f $configfile $resizefile
}

if [ -z "$1" ]
then
  echo "usage: screencssh [server] [...]" 1>&2
  exit 1
fi

configfile=$(mktemp /tmp/screencssh.XXXXXXXX) || exit 1
resizefile=$(mktemp /tmp/screencssh.XXXXXXXX) || exit 1
trap rmtmpfiles INT TERM

screen=$(basename $configfile)

config=''
config="${config}bind E quit\n"
config="${config}bind J source ${resizefile}\n"
config="${config}bind - resize -1\n"
config="${config}bind + resize +1\n"
config="${config}bind = resize =\n"
config="${config}bind j focus down\n"
config="${config}bind k focus up\n"
config="${config}bind t focus top\n"
config="${config}bind b focus bottom\n"
config="${config}msgminwait 0\n"
config="${config}msgwait 0\n"

resize=''
resize="${resize}focus bottom\n"

i=$#
for server in "$@"
do
  config="${config}screen bash -c 'ssh ${server}'\n"
  config="${config}title 'server ${server}'\n"
  config="${config}split\n"
  config="${config}focus\n"

  resize="${resize}focus up\n"
  resize="${resize}resize +${i}\n"
  (( i-- ))
done

config="${config}screen bash\n"
config="${config}title screencssh\n"
config="${config}stuff 'export SCREEN=${screen}; screencmd$(printf \\r)'\n"

resize="${resize}focus up\n"

echo -e "$config" > $configfile
echo -e "$resize" > $resizefile

screen -c $configfile -S $screen

rmtmpfiles
