#!/usr/bin/env bash
set -u  # force better programming and ability to use check for not set

if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

# this is cheap argument processing. Must be in this order when checking.
if [ "${1:-}" = "-a" ] ; then ALARM=1;       shift; else ALARM=0;        fi
if [ "${1:-}" = "-f" ] ; then FIX=/bin/true; shift; else FIX=/bin/false; fi

set +u
. /usr/local/etc/setups.sh
setup enstore
set -u

FIXIT="/usr/bin/rsync -e /home/enstore/enstore/sbin/enrsh -I -clpogtx --blocking-io"
CHECK="/usr/bin/rsync -e /home/enstore/enstore/sbin/enrsh -I -clpogtx --blocking-io --dry-run --stats"

# $Id$

node=`hostname -s`
gang=`$ENSTORE_DIR/sbin/gang`
if [ "$gang" = rip ]; then basenode=rip2; else basenode=${gang}srv1; fi

for farm in d0en stken cdfen enstore
do
  farmsrv=${farm}srv1
  case $farm in
       d0en) tag=SAM ;;
      stken) tag=STK ;;
      cdfen) tag=CDF ;;
    enstore) tag=ENS; farmsrv=$basenode ;;
  esac
  if [ $node != $farmsrv ]
  then
    $FIX && $FIXIT $farmsrv:/usr/local/etc/farmlets/${farm}* /usr/local/etc/farmlets/
    ckOut="`$CHECK $farmsrv:/usr/local/etc/farmlets/${farm}* /usr/local/etc/farmlets/ 2>/dev/null`"
    nft=`echo "$ckOut" | awk '/Number of files transferred:/ {print $NF}'`
    [ -z "$nft" ] || [ "$nft" -ne 0 ] && echo "$ckOut"
  fi
  # for now, ignore unresponsive farm server
  # later, don't ignore consecutive failures
  eval N${tag}='${nft:-0}'
done

rc=0

if [ "$NSAM" -ne 0 -o "$NSTK" -ne 0 -o "$NCDF" -ne 0 -o "$NENS" -ne 0 ]; then
    msg="BAD CONFIGURATION: Farmlet mismatch NSAM=$NSAM NSTK=$NSTK NCDF=$NCDF NENS=$NENS"
    echo $msg
    if [ $ALARM -eq 1 ]; then
       enstore alarm --raise --severity "A" --root-error "$msg"
    fi
    rc=1
else
    echo "Farmlets match, ok"
fi

# commented out for now because of Linux version incompatibilities (dmb 11/18/03)

## now check the cron.x jobs and make sure they match, too
#for f in /etc/cron.*; do
#  CHK="`$CHECK ${basenode}:$f/ $f/ 2>/dev/null`"
#  NCHK=`echo "$CHK" | awk '/Number of files transferred:/ {print $NF}'`
#  if [ $NCHK != 0 ]; then echo $f "$CHK"
#    msg="BAD CONFIGURATION: Directory $f NCHK=$NCHK"
#    echo $msg
#    if [ $ALARM -eq 1 ]; then
#       enstore alarm --raise --severity "A" --root-error "$msg"
#    fi
#    rc=1
#  else
#    echo "Directory $f, ok"
#  fi
#done

exit $rc
