#!/bin/bash

set -e

#DEBUG=1
if [ "x$DEBUG" = "x1" ]; then
    quiet=false
else
    quiet=true
fi

$quiet || echo MYSSH0: ssh "$@" >> ~/tmp/log

case "$1" in
    *"-pool-"*)
	pool="${1%-pool-*}"
	nn=($(echo "${1#*-pool-}" | sed -e "s/-/ /g"))
	target="${pool}${nn[RANDOM % ${#nn[@]}]}"
	;;
    *)
	target="$1"
	;;
esac
# Done with the first argument
shift 1

case "$1:$2:$3" in
    "sh:-c:'/tmp/"*)
	shift 2
	ftmp="$(echo "$@" | sed -e "s#.*\(/tmp/[^ ]*\).*#\1#")"
	freal="$(cat $ftmp)"
	args="$(echo "$@" | sed -e "s#$ftmp#$freal#")"
	$quiet || echo MYSSH1: ssh $target sh -c "$args" >> ~/tmp/log
	exec ssh $target sh -c "$args"
	;;
    "sh:-c:'chmod"*|"sh:-c:'rm"*|"rm:-f:/tmp/"*)
	$quiet || echo MYSSH2: ssh $(hostname) "$@" >> ~/tmp/log
	exec ssh $(hostname) "$@"
	;;
    *)
	$quiet || echo MYSSH3: ssh $target "$@" >> ~/tmp/log
	exec ssh $target "$@"
esac
