#!/bin/bash

# calls $* locally and on all other sibling hosts specified in ~/.xs2siblings/siblings resp. /etc/xs2siblings,/etc/siblings

if [ -z "$1" ] ; then
  echo "ERROR: No command given execute."
  echo "Syntax: sshsiblings [-d] [-g regex] [-q] command [cmdOptions]"
  exit 1
fi

export SLF="/etc/xs2siblings/siblings"
test -e ~/.xs2siblings/siblings && SLF=~/.xs2siblings/siblings
if [ ! -f ${SLF} ] ; then
  echo "ERROR: No sibling list, i.e. no file ~/.xs2siblings/siblings or /etc/xs2siblings/siblings"
  exit 2
fi

SHN=$(hostname -s)
export SIBLINGS=$(cat ${SLF} |egrep -v '^\s*(#|;|$)' |egrep -vi "^${SHN}(\\.|$)" |sort |uniq)
if [ -z "$SIBLINGS" ] ; then
  echo "ERROR: No siblings specified in ${SLF}."
  exit 3
fi

export GREPEXPR=""
export VERBOSITY=1
export NEXTOPTION=$(echo "$1" |egrep -- "^-")
while [ -n "$NEXTOPTION" ] ; do
  if [ "${NEXTOPTION}" = "-d" ] ; then
    shift
    VERBOSITY=3
  elif [ "${NEXTOPTION}" = "-g" ] ; then
    shift
    GREPEXPR="$1"
    shift
    test $VERBOSITY -gt 2 && echo "DEBUG: Going to egrep for '${GREPEXPR}'"
  elif [ "${NEXTOPTION}" = "-q" ] ; then
    shift
    VERBOSITY=0
  elif [ "${NEXTOPTION}" = "-v" ] ; then
    shift
    VERBOSITY=2
  fi
  NEXTOPTION=$(echo "$1" |egrep -- "^-")
done

test -n "${GREPEXPR}" -a $VERBOSITY -gt 1 && echo "INFO: Going to egrep for '${GREPEXPR}'"
test $VERBOSITY -gt 0 && echo "INFO: Calling locally ..."
if [ -n "${GREPEXPR}" ] ; then
  $* |egrep "${GREPEXPR}"
else
  $*
fi

#echo "Siblings are: $SIBLINGS"

for SIBLING in $SIBLINGS
do
  SIBLINGNAME=$(echo "$SIBLING" |cut -f1 -d':')
  SIBLINGPORT=$(echo "$SIBLING" |cut -f2 -d':')
  test $VERBOSITY -gt 0 && echo "INFO: Calling on $SIBLING ..."
  if [ "$SIBLINGPORT" = "$SIBLINGNAME" ] ; then
    test $VERBOSITY -gt 2 && echo "DEBUG: Calling on $SIBLING without special ssh options ..."
    if [ -n "${GREPEXPR}" ] ; then
      ssh $SIBLING $* |egrep "${GREPEXPR}"
    else 
      ssh $SIBLING $*
    fi 
  else 
    test $VERBOSITY -gt 2 && echo "DEBUG: Calling on $SIBLINGNAME with '-p $SIBLINGPORT' ..."
    if [ -n "${GREPEXPR}" ] ; then
      ssh -p $SIBLINGPORT $SIBLINGNAME $* |egrep "${GREPEXPR}"
    else 
      ssh -p $SIBLINGPORT $SIBLINGNAME $*
    fi 
  fi 
done

