#!/bin/sh -e

##########################################################################
#   Script description:
#       Shut down the entire cluster in a rational order
#       
#   History:
#   Date        Name        Modification
#   2014-01-16  J Bacon     Begin
##########################################################################

usage()
{
    printf "Usage: $0 \n"
    exit 1
}


##########################################################################
#   Main
##########################################################################

if [ $# != 0 ]; then
    usage
fi

cluster-head-check $0

set +e

os_type=`auto-ostype`
case $os_type in
FreeBSD)
    auto-group-check wheel $0
    flag='-p'
    ;;

RHEL)
    auto-root-check $0
    flag='-h'
    ;;

*)
    printf "$0: Not supported on $(auto-ostype).\n"
    exit 1
    ;;

esac

printf "Shut down compute nodes? (yes/[no]) "
read compute

if [ 0$(cluster-file-servers) != 0 ]; then
    printf "Shut down file servers? (yes/[no]) "
    read file_servers
fi

if [ 0$(cluster-vis-nodes) != 0 ]; then
    printf "Shut down visualization nodes? (yes/[no]) "
    read vis
fi

if [ 0$(cluster-backup-nodes) != 0 ]; then
    printf "Shut down backup login nodes? (yes/[no]) "
    read backup
fi

printf "Shut down head node? (yes/[no]) "
read head

if [ 0$compute = 0yes ]; then
    for node in `cluster-compute-nodes`; do
	if ping -c 1 -q $node > /dev/null 2>&1; then
	    printf "Shutting down $node...\n"
	    ssh $node shutdown $flag now || true
	else
	    printf "$node is not responding.  Moving on...\n"
	fi
    done
fi

if [ 0$file_servers = 0yes ]; then
    cluster-run -c "shutdown $flag now" io || true
fi

if [ 0$vis = 0yes ]; then
    cluster-run -c "shutdown $flag now" vis || true
fi

if [ 0$backup = 0yes ]; then
    cluster-run -c "shutdown $flag now" backup || true
fi

if [ 0$head = 0yes ]; then
    shutdown $flag now
fi
