#!/bin/bash
#==============================================================
# screenlogd.bash
#
# ARGUMENTS:
#
# OPTION:     
#
# Facility:  SLAC/LCLS
#
# Auth:  07-Jun-2005, Jingchen Zhou   (JINGCHEN)
# Rev:   dd-mmm-yyyy, Reviewer's Name (USERNAME)
#
# Rem:   Screen logging management
#        - save screenlog.0 to screenlog.0-$CURRTIMESTAMP
#        - screenlog.0 will be recreated automatically by Screen program 
#           if removed.        
#        - Keep 3 copies of screenlog.0-$CURRTIMESTAMP
#        - run as cron job
#        - Note: automatic restart of the screen logging daemon will be added 
#----------------------------------------------------------------------------
# Mod:
#       5-Feb-2020, Ken Brobeck (brobeck)
#       Adding new email for CPUs
#       28-Jan-2020, Ken Brobeck (brobeck)
#       Added CPU IOCs to the monitoring of screenlog.0 checks
#       30-Nov-2018, Ken Brobeck (brobeck)
#       Modified sed command so special charactors did not mess up email
#       Added dos2unix command as well
#       20-Nov-2018, Ken Brobeck (brobeck)
#       Had to remove "degree" (°) symbole from file -to email
#       19-Nov-2018, Ken Brobeck (brobeck)
#       Added full name to MAILLIST (@slac.stanford.edu)
#       08-Nov-2018, Ken Brobeck (brobeck)
#       If screenlog.0 is over 1 MB:
#         Create backup screenlog.0 name as screenlog.0-$CURRTIMESTAMP
#         Send Email to IOC Engineer (CONTACT) with the last 5 lines of log
#         Keep 3 copies and the current screenlog.0
#         Send Master report to Controls Deputy
#       Under 1 MB do nothing
#       05-Nov-2018, Ken Brobeck (brobeck)
#       Keeping 7 screenlogd files if less than 1MB in size
#       09-Oct-2018, Ken Brobeck (brobeck)
#       Create backup screenlog.0 name as screenlog.0-$CURRTIMESTAMP
#       Move over screenlog.0 to backup file every day
#       Keep 3 copies of backup file
#       Send email if screenlog.0 is over 1Mb in size -Could be a problem
#       Changed Email to controls-system-admins
#       16-Mar-2014, Judy Rock (jrock)
#       removed jrock from email list
#       30-Mar-2011, Judy Rock (jrock)
#       for soft IOCs screenlogd check, first find which host (siocs are now on lcls-daemon0 and lcls-daemon1)
#       11-Jan-2011, Judy Rock (jrock)
#       add check for screenlog.0 for soft iocs
#       31-Aug-2010, Judy Rock (jrock)
#       remove backup files over 7 days old, but only if there is a screenlog.0 AND
#       if there are at least 2 backup copies. backup files are named screenlog.timestamp
#       instead of screenlog.1
#       24-Aug-2010, Judy Rock (jrock)
#       added call to check_screenlogdLog.bash to check for errors
#       11-Aug-2010, Judy Rock (jrock)
#       - added call to createDetachedScreen.bash to create SCREEN process to resume screen logging
#       - modified screeniocs grep command for lcls
#       23-Feb-2009, Jingchen Zhou (JINGCHEN)
#       - rotate screenlog.o to screenlog.1 by size (1m) instead of by time
#       - remove screenlog.1 if older than one week.
#       10-Jun-2008, Jingchen Zhou (JINGCHEN)
#       - updated to support the standalone production environment for LCLS
#       - comment out reporting if IOC console logging is not up
#       09-Jun-2007, Jingchen Zhou (JINGCHEN)
#       - adapted from PEPII version and tuned it to work for LCLS  
#       29-Jun-2005, Jingchen Zhou (JINGCHEN)
#       - exclude development IOCs in reporting.
#       31-May-2005, Jingchen Zhou (JINGCHEN)
#       - report if IOC console logging is not up.
#         will be improved to auto-restart the IOC console logging as soon
#         as a way to terminate the interactive session in a script is 
#         figured out.   
#       - report if the size of current screenlog grows over 1MB
#       - rotate screenlog.o to screenlog.1 if older than 1 day   
#==============================================================
#
EMAIL="controls-system-admins@slac.stanford.edu controls-cd@slac.stanford.edu"
#----------------------------------------------
# If no CONTACT defined it will go to DEFEMAIL
#----------------------------------------------
DEFEMAIL="controls-cd@slac.stanford.edu"
CPUEMAIL="ernesto@slac.stanford.edu"
emailcmd="/usr/bin/Mail -s $0 ${EMAIL}"

#-------------------
# Set up LCLS_ROOT
#-------------------
if [ -d /afs/slac/g/lcls ]; then
   export SCREEN_HOST=lcls-dev1
   export SEARCH_SCREEN_HOST=lcls-dev
   export LCLS_ROOT=/afs/slac/g/lcls
else 
   export SCREEN_HOST=lcls-daemon1
   export SEARCH_SCREEN_HOST=lcls-daemon
   export LCLS_ROOT=/usr/local/lcls 
fi
#-------------------
# Set up LCLS_DATA
#------------------
if [ -d /nfs/slac/g/lcls ]; then
   export LCLS_DATA=/nfs/slac/g/lcls  
else
   export LCLS_DATA=/u1/lcls
fi

IOC_SCREEN=$LCLS_ROOT/epics/iocCommon
IOC_DATA=$LCLS_DATA/epics/ioc/data
#---------------------------------------------------------------------------------
# go through all the hard iocs (ioc-*, eioc-*)
# createDetachedScreen.bash checks for a screen process and socket file
# if these aren't found, creates a new screen session.
# the new screen process will write to the existing screenlog.0; if the file
# is not found, it will create one
#---------------------------------------------------------------------------------
echo STARTING SCREEN PROCESSES THAT NEED IT...
iocs=`grep ^[e]*ioc-.*$SCREEN_HOST $IOC_SCREEN/screeniocs | awk '{print $1}'`
for i in $iocs
do
  echo checking screen process for $i
  $LCLS_ROOT/tools/script/createDetachedScreen.bash $i
done

/usr/local/lcls/tools/script/check_screenlogdLog.bash
cat /tmp/screenlogdLogErrList.log | Mail -s "screenlogd createDetachedScreen errors" jingchen@slac.stanford.edu
#-----------------------------------------------------------------
# now cleanup oversized screenlog.0, and old screenlog.1 files
#-----------------------------------------------------------------
cd $IOC_DATA
if [ $? -ne 0 ]; then                
    echo ERROR: $IOC_DATA not available   
    exit 1
fi
#------------------------------------------------------------------------
# first, check soft iocs for screenlog.0
# for each soft ioc with a socket file, make sure there's a screenlog.0
#------------------------------------------------------------------------
siocs=`grep ^sioc-.*$SEARCH_SCREEN_HOST $IOC_SCREEN/screeniocs | awk '{print $1 ":" $4}'`

echo LIST OF PRODUCTION SOFT IOCS > /tmp/siocsMissingScreenlog.txt
echo - WITH SCREEN PROCESS AND >> /tmp/siocsMissingScreenlog.txt
echo - MISSING SCREENLOG.0 FILE >> /tmp/siocsMissingScreenlog.txt

for i in $siocs
do
   IOC=`echo $i | cut -d ":" -f 1`
   IHOST=`echo $i | cut -d ":" -f 2`

   echo checking $IOC on $IHOST
   numPROCS=`ssh $IHOST  -l laci ps -ef | grep " $IOC" | grep SCREEN | wc -l`

   if [ $numPROCS -gt 0 ]; then
      if [ -e $IOC_DATA/$IOC/screenlog.0 ]; then
         echo screenlog file exists for soft IOC $IOC
      else
         echo NO screenlog file exists for soft IOC $IOC
         echo $IOC >> /tmp/siocsMissingScreenlog.txt
      fi

   fi
done

echo END OF LIST >> /tmp/siocsMissingScreenlog.txt
cat /tmp/siocsMissingScreenlog.txt  | Mail -s "SIOCs missing screenlog.0 files" jingchen@.slac.stanford.edu
#--------------------------------------------------------------------
# go through each IOC_DATA dir: backup and cleanup screenlog files
#--------------------------------------------------------------------
echo CLEANING UP screenlog FILES
CURRTIMESTAMP=`date '+%Y%m%d%H%M%S'`
#----------------------------------------------------------------------
# Create a file (FILELIST) to store names of large screenlog.0 files
# Run epicsReset.bash for caget command
#----------------------------------------------------------------------
if [ -d /afs/slac/g/lcls ]; then 
        export LCLS_ROOT=/afs/slac/g/lcls
else
        export LCLS_ROOT=/usr/local/lcls
fi
# Source group environment setup for EPICS
if [ -f ${LCLS_ROOT}/epics/setup/epicsReset.bash ]; then
    . ${LCLS_ROOT}/epics/setup/epicsReset.bash
fi

FILELIST=/tmp/large-screenlog-files
rm -f $FILELIST
# Create Email file
EFILE=/tmp/screenlogd-email
rm -f $EFILE

# Added cpus for Realtime Linux servers (only for screenlog.0 log file maintenance)
cpus=`grep ^cpu-.*$SEARCH_SCREEN_HOST $IOC_SCREEN/screeniocs | awk '{print $1}'`
iocs=`grep ^[es]*ioc-.*$SEARCH_SCREEN_HOST $IOC_SCREEN/screeniocs | awk '{print $1}'`

IOCS="$cpus $iocs"

for i in $IOCS
do
   echo cleanup for $i
   #-----------------------------------------------------------------------------------------------
   # If screenlog.0 is larger than 1000k then write name to a FILELIST
   # Get CONTACT info and send email. 
   # Move over screenlog.0 to backup name: screenlog.0-$CURRTIMESTAMP
   # -Will only move files over 1MB and keep 3 copies
   # Files under 1MB will not be touched
   #-----------------------------------------------------------------------------------------------
   if [ -e $IOC_DATA/$i/screenlog.0 ]
    then
       if [ `du -sk $IOC_DATA/$i/screenlog.0 | awk '{print $1}'` -gt 1000 ]
         then
	   # Translate Name to PV style
	   TNAME=`echo $i | /usr/bin/tr [:lower:] [:upper:] | /usr/bin/tr - :`
	   # Get Contact info and mail address
	   POC=`caget ${TNAME}:CONTACT`
	   # Make sure contact is defined
	   if [ "$?" == 1 ]
	     then 
	       POC="${TNAME}:CONTACT  :  Contact not defined"
	       # Try the ENGINEER PV POC to see if this is defined
	       EPOC=`caget ${TNAME}:ENGINEER`
	       EPOCMLNAME=`echo $EPOC | awk -F "[()]" '{print $2}'`
	       if [ "$EPOCMLNAME" == "" ]
		   then
                     #--------------------------------------------
		     # CPUs do not have CONTACTs and CD does not
		     # want to see these emails - so different
		     # email is setup
		     #--------------------------------------------
		     if [[ "$i" == cpu* ]]
                        then
                           MAILLIST=$CPUEMAIL
                        else
                           MAILLIST=$DEFEMAIL
                     fi
		   else
		     MAILLIST=$EPOCMLNAME
	       fi
	     else
	       MLNAME=`echo $POC | awk -F "[()]" '{print $2}'`
	       MAILLIST="${MLNAME}@slac.stanford.edu"
	   fi
	   #-----------------------------------------------------------
	   # Make a list of large files for the "tail" command below
	   #-----------------------------------------------------------
	   echo " $i" >> $FILELIST
	   #---------------------------------------
	   # Create temp file to email to CONTACT
	   #---------------------------------------
	   TFILE=/tmp/tempfile
	   rm -f $TFILE
	   printf "\n\t$POC\n" | tee -a  $EFILE $TFILE
	   ls -lh $IOC_DATA/$i/screenlog.0 | tee -a $EFILE $TFILE
	   #printf "\t$POC\n" >> $TFILE
	   #ls -lh $IOC_DATA/$i/screenlog.0 >> $TFILE
	   printf "\nMoving to $IOC_DATA/$i/screenlog.0-$CURRTIMESTAMP\n\n" >> $TFILE
           tail -n 5 $IOC_DATA/$i/screenlog.0 >> $TFILE
           # Remove special characters so email works
	   /usr/bin/dos2unix $TFILE
	   cat $TFILE | sed -e 's/[^a-zA-Z*0-9, -\/]/ /g;s/  */ /g;s/\°/ /g' | \
                tr -cd '\11\12\15\40-\176' | \
                mailx -s "$IOC_DATA/$i/screenlog.0 is over 1MB" "$MAILLIST"
	   #----------------------------------------------------------------------------
	   # Since file is over 1MB make copy and create new screenlog.0 file by delete
	   #----------------------------------------------------------------------------
	   cp -p $IOC_DATA/$i/screenlog.0 $IOC_DATA/$i/screenlog.0-$CURRTIMESTAMP
           rm $IOC_DATA/$i/screenlog.0
   	   #-------------------------------------------------------------------
   	   # Keep 3 copies screenlog.0-$CURRTIMESTAMP files
   	   #-------------------------------------------------------------------
   	   LIST=`ls -t $IOC_DATA/$i/screenlog.0-* | tail -n +4`
   	   for x in $LIST
   	   do
       	      rm -f $x
   	   done
       fi

    else
       echo "$IOC_DATA/$i/screenlog.0 does not exist"
   fi      
done
#---------------------------------------------------
#Print the last 5 lines of log file to Master EFILE
#---------------------------------------------------
for x in `cat $FILELIST`
do
    printf "\n\n---- $IOC_DATA/$x/screenlog.0 ----\n\n" >> $EFILE
    tail -n 5 $IOC_DATA/$x/screenlog.0-$CURRTIMESTAMP >> $EFILE
done
#----------------------------------------------
# Make sure there is something to email &
# Remove special characters
# Degree symbol - remove lines with °
#----------------------------------------------
if [ `du -sb $EFILE | awk '{print $1}'` -gt 100 ]
 then
        /usr/bin/dos2unix $EFILE
	cat $EFILE | sed -e 's/[^a-zA-Z*0-9, -\/]/ /g;s/  */ /g;s/\°/ /g' | \
                tr -cd '\11\12\15\40-\176' |  $emailcmd
fi

echo DONE

exit 0

