#!/bin/bash 
#
if [ `uname -n` != "lcls-uwd" ]
    then
       echo ""
       echo " Can only run on lcls-uwd"
       echo ""
       exit
fi
ServerList=`cat /afs/slac/g/lcls/tools/uwd/config/Server-list`
DirList="rc3.d init.d"
Mail_List="brobeck@slac.stanford.edu"

WDIR="/nfs/slac/g/lcls/sys/uwd"

#
# Go through the server list and get the 'ls -l" listings for rc3.d
# and copy the 'st.*' filed from the init.d directories.
# perform a "diff" on each file and send mail when there are any 
# changes.
#
# Push the files to the "OLD" directories to make room for the
# new files...and just cycle the files
#
#
for x in $ServerList
do
   # Make the direcories if not made already
   if [ ! -d $WDIR/$x ] 
     then 
        mkdir -p $WDIR/$x/init.d/OLD
        mkdir -p $WDIR/$x/rc3.d/OLD
	mkdir -p $WDIR/$x/crontab
   fi

   #
   # go through the 'rc3.d and init.d' directories
   #
   for i in $DirList
   do
      #
      # get the listings of the dirs (rc3.d & init.d)
      # and put them in a file  put the old copies into 
      # OLD and perform a diff
      #
      # check to see if any files exists -move the files
      # to the OLD directory.
      #	 	
      DirItems=`ls $WDIR/$x/$i/ | wc -l`
      if [ "$DirItems" -gt 0 ]
        then
           rm -f $WDIR/$x/$i/OLD/*
           mv -f $WDIR/$x/$i/*listing* $WDIR/$x/$i/OLD/
           HasST=`ls -d $WDIR/$x/$i/* | grep 'st\.' > /dev/null; echo $?`
	   if [ "$HasST" = "0" ]
             then
           	mv -f $WDIR/$x/$i/st.* $WDIR/$x/$i/OLD/
	   fi
      fi
      #
      # Get a directory listing and see if any files have been added or removed
      #
      ssh -xl laci $x "ls -l /etc/$i/*st.*" | grep -v \~ > $WDIR/$x/$i/$i-listing
     
      # Copy over the init.d files ( st.* ) 
      if [ "$i" = "init.d" ]
        then
	      scp -qp laci@$x:/etc/init.d/st.*  $WDIR/$x/$i/
	      rm -f $WDIR/$x/$i/*~
      fi

      # Now let's do some diffs -send mail if there are
      # any differences
      #
      diff $WDIR/$x/$i/$i-listing $WDIR/$x/$i/OLD/$i-listing \
           >  $WDIR/$x/$i/$i-listing-diffs

      success=$?
      if [ "$success" = 1 ]
	then
	  cat $WDIR/$x/$i/$i-listing-diffs | mailx -s "$x - $i has changed" $Mail_List
      fi

      #
      # Check the startup files in init.d for differences and mail any changes
      #
      cd $WDIR/$x/init.d
      LIST=`ls *st.* | grep -v diffs`
      for g in $LIST
      do
	diff $WDIR/$x/init.d/$g $WDIR/$x/init.d/OLD/$g > $g-diffs
	success=$?
	if [ "$success" = 1 ]
          then
	    cat $g-diffs | mailx -s "$x -$g has Changed" $Mail_List
     	fi

      done  #$LIST

   done  #DirList

      # copy over the crontab file
      # -most do not have a crontab file
      #
      rm -f $WDIR/$x/crontab/crontab.old
      mv -f $WDIR/$x/crontab/crontab.new $WDIR/$x/crontab/crontab.old
      ssh -xl laci $x "crontab -l"   > $WDIR/$x/crontab/crontab.new

done  #ServerList
