#!/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 graceful cluster shutdown script.
#
# usage: See sw-stop-cluster -h

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

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

while [ $# -gt 0 ]
do
  case $1
  in
    -v)
      VERBOSE=1
      shift 1
    ;;

    -f)
      if [[ $2 = '--' ]]; then
         # STDIN input
         SOURCE=''
      else
         # Cluster definition file
         SOURCE=$2
      fi
      shift 2
    ;;

    --mp)
      MASTER_PORT=$2
      shift 2
    ;;

    --wp)
      WORKER_PORT=$2
      shift 2
    ;;
    
    -h|*)
      echo "Shuts down a cluster using HTTP RPCs."
      echo "usage: sw-stop-cluster [-f cluster-file|-v]"
      echo "-f: the file listing the machines in the cluster, one per line."
      echo "    If '--' is passed, STDIN is assumed."
      echo "--mp: specifies a master port (default: 8000)."
      echo "-v: verbose mode (don't surpress output from curl)"
      echo "--wp: specifies a worker port (default: 8001)."
      shift 1
      exit 0
    ;;
  esac
done

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

I=0
cat $SOURCE | while myLine=`line`
do
    echo -n "Stopping instance $I "
    if [ "$I" -eq "0" ]; then
	echo "... (master)."
	if [ $VERBOSE -eq 1 ]; then
	    curl http://$myLine:${MASTER_PORT}/shutdown/
	else
	    curl -s http://$myLine:${MASTER_PORT}/shutdown/
	fi
	MASTER=$myLine
    else
	echo "... (worker for $MASTER)"
	if [ $VERBOSE -eq 1 ]; then
	    curl http://$myLine:${WORKER_PORT}/kill/
	else
	    curl -s http://$myLine:${WORKER_PORT}/kill/
	fi
    fi
    I=`expr $I + 1`
done

exit 0
