#!/bin/sh
####################################################################
# (C) Copyright 2005-2005 Hewlett-Packard Development Company, L.P.
# @(#) cmdo: execute a command on nodes within configured cluster.
# @(#) Product Version           :  A.12.10.00
# @(#) Patch Name                :  
#####################################################################

#PATH=$SGSBIN:/usr/bin:/usr/sbin:/opt/VRTS/bin

. ${SGCONFFILE:=/etc/cmcluster.conf}

print_usage ()
{
    echo "Usage: cmdo [ [-n node] ... ] [-t timeout] cmd [cmd_option...]"
    echo "       cmdo [ [-n node] ... ] [-t timeout] -k cmd_label"
    exit 1
}

# Initialize vars
node_list=""
other_opts=""
cmd_args=""
end_opts=0

# Loop through arguments and options, parsing -n for cmdo
# use, passing -k and -t and the command to cmexec, and
# disallowing any other options
while [ $# -gt 0 ]; do
    case "$1" in
        -n) if [ $# -gt 1 ]; then
                node_list="$node_list $2"
                shift 2
            else
                print_usage
            fi ;;
        -k|-t)  if [ $# -gt 1 ]; then
                    other_opts="$other_opts $1 $2"
                    shift 2
                else
                    print_usage
                fi ;;
        -*) if [ $end_opts -eq 0 ]; then
                print_usage 
            else
                cmd_args="$cmd_args $1"
                shift
            fi ;;
        *)  cmd_args="$cmd_args $1"
            end_opts=1
            shift ;; 
    esac
done

# Verify that a command was specified
if [[ -z "$cmd_args" && -z "$other_opts" ]]; then
    print_usage
fi

# If no node is specified, automatically select all in local cluster
if [ -z "$node_list" ]; then
    node_list=`$SGSBIN/cmviewcl -f line -l node | grep '|name=' | cut -f2 -d'='`
     if [ -z "$node_list" ]; then
        echo "Error: cannot read cluster configuration. You must specify node(s)."
        exit 1
    fi
fi

# Execute on each node in node_list
ret=0
for node in ${node_list}
do
    echo "## Executing on node ${node}:"
    $SGSBIN/cmexec $node $other_opts $cmd_args
    if [ $? -ne 0 ]; then
        ret=1
    fi
done
exit $ret 
