#/bin/sh
#
# -*- mssh -*-
#
# mssh: ssh multiplexer using tmux
#
#  (following the excellent idea of Christoph Egger:
#      http://www.christoph-egger.org/weblog/entry/33)
#
# Author: 2011, Emmanuel Bouthenot <kolter@openics.org>
#
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more details.
#

internal=0
internal_opt="--internal"

usage() {
	printf "Usage: %s host1 ... hostN\n" $1
}

if [ "$1" = "$internal_opt" ]; then
	internal=1
	shift
fi

TMUXBIN=$(which tmux)
if [ $? != 0 ]; then
	printf "Error: %s needs tmux to run, could't find it in \$PATH\n" "$(basename "$0")"
	exit 1
fi

if [ -n "$TMUX" ] && [ $internal = 0 ]; then
	printf "Error: %s should not be run inside tmux\n" "$(basename "$0")"
	exit 1
fi

if [ $# = 0 ]; then
	usage
	exit 2
fi

if [ $internal = 1 ]; then
	for i in $* ; do
		$TMUXBIN splitw "ssh $i"
		$TMUXBIN select-layout tiled
	done
	$TMUXBIN set-window-option synchronize-panes on
else
	$TMUXBIN new "exec $(readlink -f "$0") "$internal_opt" $*"
fi

