#!/bin/bash
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#

usage() {
    echo "Usage: $0 [options] command.
Run a command on each host in \$HOSTS.
Options:
  -l USER     passed to ssh - run as USER.
  -t          passed to ssh - create a terminal.
  -b          run in background, wait for commands to complete.
  -d          run in background, don't wait for commands to complete.
  -s SECONDS  sleep between starting commands.
  -q          don't print banner lines for each host.
  -o SUFFIX   log output of each command to <host>.SUFFIX
  -X          passed to ssh - forward X connection.
"
    exit 1
}

while getopts "tl:bs:dqo:X" opt; do
    case $opt in
	l) SSHOPTS="-l$OPTARG $SSHOPTS" ;;
	t) SSHOPTS="-t $SSHOPTS" ;;
	b) BACKGROUND=1 ;;
	d) BACKGROUND=1; DISOWN=1 ;;
	s) SLEEP="sleep $OPTARG" ;;
	q) NOBANNER=1 ;;
	o) SUFFIX=$OPTARG ;;
	X) SSHOPTS="-X $SSHOPTS" ;;
	*) usage;;
    esac
done
shift `expr $OPTIND - 1`
test "$*" || usage;

OK_FILE=`mktemp`		# Will be deleted if anything goes wrong.
trap "rm -f $OK_FILE" EXIT

do_ssh() {
    h=$1; shift
    if test $SUFFIX ; then ssh $SSHOPTS $h "$@" &> $h.$SUFFIX
    else ssh $SSHOPTS $h "$@"; fi || rm -rf $OK_FILE;
}

for h in $HOSTS ; do
    test "$NOBANNER" || echo "== ssh $SSHOPTS $h $@ =="
    if [ "$BACKGROUND" = 1 ]; then
	do_ssh $h "$@" &
	CHILDREN="$! $CHILDREN"
    else
	do_ssh $h "$@"
    fi
    $SLEEP
done

if [ "$DISOWN" = 1 ]; then
    for c in $CHILDREN; do disown $c; done
else
    wait
fi

test -f $OK_FILE
