#!/bin/sh

if [ "" = "$FARMLETS" ]
then
   FARMLETS=/usr/local/etc/farmlets
   export FARMLETS
fi

if [ ! -d $FARMLETS ]
then
   echo "Farmlet directory $FARMLETS does not exist "
fi

if [ "$#" = 0 ]
then
        set : -h
        shift
fi

copyit=0
header=1
skipit=0

case "$1" in
-h*|-\?*) echo "usage:  $0 farmlet 'cmd1' 'cmd2'...     -- run cmds on hosts"
          echo "        $0 -l                           -- list farmlets"
          echo "        $0 -d                           -- directory of farmlets"
          echo "        $0 -h                           -- list print this help"
          echo "        $0 -n                           -- don't print header"
          echo "        $0 -s                           -- skip current node"
          echo "        $0 -c                           -- copy input output"
          exit
        ;;
-l)     cd $FARMLETS
        for i in *
        do
                echo "FARMLET $i:"
                cat $i
        done
        exit
        ;;
-d)     ls $FARMLETS
        exit
        ;;
-c)     copyit=1
        shift
        ;;
-C)     copyit=1
        skipit=1
        shift
        ;;
-n)     header=0
        shift
	;;
-nn)    header=2
        shift
        ;;
-N)     header=0
        skipit=1
        shift
        ;;
-s)     skipit=1
        shift
        ;;
esac
case $1 in

*:*)    listfile=/tmp/gang$$
        farmlist $1 > $listfile
        shift
        ;;
*)
        if [ -f "$1" ]
        then
                listfile=$1
                shift
        elif [ -r $FARMLETS/$1 ]
        then
                listfile=$FARMLETS/$1
                shift
        else
                echo "ERROR can not read farmlet file $FARMLETS/$1"
                exit 1
        fi
        ;;
esac

thisnode=`uname -n | sed -e 's/.fnal.gov//'`
for machine in `cat $listfile`
do
        if [ $skipit -eq 1 -a "$machine" = "$thisnode" ]; then continue; fi
        #netaddr=`grep $machine /etc/hosts | sed -e 's/ .*//'`
        #gateway=`grep $machine /etc/hosts | sed -e 's/.*gateway //'`
        if [ $header -eq 1 ]; then
          echo
          echo "- - - - - - - - - - - - - - $machine - - - - - - - - - - - - - -"
        elif [ $header -eq 2 ]; then
          echo -n "$machine= "
        fi
        if [ $copyit = 0 ]; then
           for command in "$@"
              do
                if [ $header -eq 1 ];then echo enrsh $machine \""$command"\"; fi
                eval enrsh $machine \""$command"\"
           done
        else
                if [ $header -eq 1 ]; then echo enrcp $1 $machine:$2; fi
                     enrcp $1 $machine:$2
        fi

done

rm -f /tmp/gang$$
