#!/bin/bash
# Copyright (c) 2010 Malte Schwarzkopf <malte.schwarzkopf@cl.cam.ac.uk>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# ----
#
# Skywriting/Ciel helper script to run a command on all machines in a cluster.
#
# usage: See sw-run-command -h

# defaults
KEY="sw-masterkey"
SWUSER="root"
SWROOT="/opt/skywriting"
VERBOSE=0

# ---------------------------------------------
# option processing

while [ $# -gt 0 ]
do
  case $1
  in
    -c)
      COMMAND=$2
      shift 2
    ;;

    -i|-k)
      KEY=$2
      shift 2
    ;;

    -f)
      if [[ $2 = '--' ]]; then
         # STDIN input
         SOURCE=''
      else
         # Cluster definition file
         SOURCE=$2
      fi
      shift 2
    ;;
    
    -r|--swroot)
      SWROOT=$2
      shift 2
    ;;
    
    -u|--swuser)
      SWUSER=$2
      shift 2
    ;;

    -v)
      VERBOSE=1
      shift 1
    ;;
    
    -h|*)
      echo "Runs a given command on all machines in the cluster."
      echo "usage: sw-run-command -c command [-f cluster-file|(-i|-k) key|-r swroot|-u swuser|-v]"
      echo ""
      echo "-c: command to be run on the cluster machines"
      echo "-f: the file listing the machines in the cluster, one per line."
      echo "    If '--' is passed, STDIN is assumed."
      echo "-i|-k: the private key to use for authentication to cluster machines"
      echo "       (defaults to 'sw-masterkey')"
      echo "-r|--swroot: the root directory of the remote Skywriting installation"
      echo "             (defaults to '/opt/skywriting')"
      echo "-u|--swuser: the user name of the Skywriting user on the cluster"
      echo "             (defaults to 'root')"
      echo "-v: verbose mode (don't surpress output from remote machines)"
      shift 1
      exit 0
    ;;
  esac
done

# ---------------------------------------------
# main script

if [[ $COMMAND == "" ]]; then
   echo "command (-c) must be specified!"
   exit 2
fi

exec 3<$SOURCE
I=0
while read -u 3 myLine
do
    echo -n "Running command on instance $I: "
    if [[ $VERBOSE -eq 1 ]]; then
	ssh -o StrictHostKeyChecking=no -f -i $KEY $SWUSER@$myLine $COMMAND
    else
	ssh -o StrictHostKeyChecking=no -f -i $KEY $SWUSER@$myLine $COMMAND 1>&2 2>/dev/null
    fi
    echo $myLine
    I=`expr $I + 1`
done

exit 0
