#!/bin/bash
#                      /usr/local/bin/my_twin
# http://crystalfaeries.net/posix/bin/my_twin
# celeste:crystalfaery 2016-07-03 16:35:28+00:00
# my_twin is a helper for commands like rsync,
# to determine the source or destination of the rsync,
# from me to my twin, or vice versa.
# This facilitates a single script working between multiple hosts, e.g.:
# rsync -auvzH source_specification `my_twin`:/destination

# If called with the argument "-h" then the hostname only is returned, rather than user@hostname.
let hostname_only=1		# false by default
if [[ $# -ne 0 ]]
then				# we have an argument
    case "$1" in
-h)
	let hostname_only=0	# true by argument
	;;
*)
	echo "$0 does not cognize argument $1" 1>&2
	exit -1
	;;
    esac
fi

case `hostname` in
fey)
	if   $(ping -q -c 1 faerie > /dev/null)
	then	# we prefer to twin with faerie which has the most disk space
		if [[ $hostname_only -eq 0 ]]
		then
			echo	"faerie"
		else
			echo	"$(whoami)@faerie"
		fi
	elif $(ping -q -c 1 pixy > /dev/null)
	then	# versus pixy which has less disk space
		if [[ $hostname_only -eq 0 ]]
		then
			echo	"pixy"
		else
			echo	"$(whoami)@pixy"
		fi
	else	# we have no twin currently online so talk to self
		if [[ $hostname_only -eq 0 ]]
		then
			echo	"localhost"
		else
			echo	"$(whoami)@localhost"
		fi
	fi
	exit 0
	;;
pixy)
	if   $(ping -q -c 1 fey > /dev/null)
	then	# we prefer to twin with fey which has the most disk space second to self
		if [[ $hostname_only -eq 0 ]]
		then
			echo	"fey"
		else
			echo	"$(whoami)@fey"
		fi
	elif $(ping -q -c 1 faerie > /dev/null)
	then	# versus faerie which has little disk space
		if [[ $hostname_only -eq 0 ]]
		then
			echo	"faerie"
		else
			echo	"$(whoami)@faerie"
		fi
	else	# we have no twin currently online so talk to self
		if [[ $hostname_only -eq 0 ]]
		then
			echo	"localhost"
		else
			echo	"$(whoami)@localhost"
		fi
	fi
	exit 0
	;;
faerie)
	if   $(ping -q -c 1 fey > /dev/null)
	then	# we prefer to twin with fey which has the most disk space
		if [[ $hostname_only -eq 0 ]]
		then
			echo	"fey"
		else
			echo	"$(whoami)@fey"
		fi
	elif $(ping -q -c 1 pixy > /dev/null)
	then	# versus pixy which has the least disk space
		if [[ $hostname_only -eq 0 ]]
		then
			echo	"pixy"
		else
			echo	"$(whoami)@pixy"
		fi
	else	# we have no twin currently online so talk to self
		if [[ $hostname_only -eq 0 ]]
		then
			echo	"localhost"
		else
			echo	"$(whoami)@localhost"
		fi
	fi
	exit 0
	;;
*)
	if [[ $hostname_only -eq 0 ]]
	then
		echo	"localhost"
	else
		echo	"nobody@localhost"
	fi
	echo "$0 does not cognize host `hostname`" 1>&2
	exit -3
	;;
esac


syntax highlighted by Code2HTML, v. 0.9.1