#!/bin/bash

# spread command over multiple servers

SPREAD_SERVERS=${SPREAD_SERVERS:-}
SPREAD_SERVERS_FILE=${SPREAD_SERVERS_FILE:-servers.txt}
SPREAD_USER=${SPREAD_USER:-$USER}
SPREAD_COMMAND=${SPREAD_COMMAND:-}

while getopts "s:f:u:" opt; do
    case $opt in
    s)
        SPREAD_SERVERS="$SPREAD_SERVERS $OPTARG"
        ;;
    f)
        SPREAD_SERVERS_FILE="$SPREAD_SERVERS_FILE $OPTARG"
        ;;
    u)
        SPREAD_USER="$OPTARG"
        ;;
    \?)
        echo "Invalid option: -$OPTARG" >&2
        ;;
    esac
done
shift $((OPTIND - 1))

if [ -n "$1" ]; then
    SPREAD_COMMAND="$@"
fi

if [ -f $SPREAD_SERVERS_FILE ]; then
    SPREAD_SERVERS="$SPREAD_SERVERS $(cat $SPREAD_SERVERS_FILE)"
fi

if [ -z "$SPREAD_SERVERS" ]; then
    echo "No servers specified"
    exit 1
fi

if [ -z "$SPREAD_COMMAND" ]; then
    echo "No command specified"
    exit 1
fi

_ssh() {
    ssh \
        -l $SPREAD_USER \
        -o ConnectTimeout=5 \
        ${SPREAD_SSH_OPTIONS:-} \
        $1 \
        "$SPREAD_COMMAND"
}

for server in $SPREAD_SERVERS; do
    # while loop so we get:: $SPEAD_USER@$server: <output>
    case ${SPREAD_LOG_STYLE:-header} in
        prefix|prefixed)
            _ssh $server | while read -r line; do
                printf "%s@%-10s: %s\n" "$SPREAD_USER" "$server" "$line"
            done
            ;;
        header)
            printf "\n%s@%s\n---\n" "$SPREAD_USER" "$server"
            _ssh $server
            ;;
        *)
            _ssh $server
            ;;
    esac
done