#!/bin/sh
set -u  # force better programming and ability to use check for not set
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

# sbin/$RCSfile$  $Revision$

# Usage: log_trans_fail

thisYear=`date +%Y`
thisMonth=`date +%m`
thisDay=`date +%d`

#Make sure to set a timeout.
timeout='--timeout 10 --retries 3'

#First obtain the directory the logs are in.
LOGS=`enstore conf $timeout --show log_server log_file_path`
if [ $? -ne 0 ]; then
   echo "Unable to obtain log directory path." > /dev/null 2>&1
   return 1
fi

#Second obtain the directory the logs are in.
HTML_DIR=`enstore conf $timeout --show crons html_dir`
if [ $? -ne 0 ]; then
   echo "Unable to obtain log directory path." > /dev/null 2>&1
   return 1
fi

#Third obtain the directory the logs are in.
WEB_SERVER=`enstore conf $timeout --show crons web_node`
if [ $? -ne 0 ]; then
   echo "Unable to obtain log directory path." > /dev/null 2>&1
   return 1
fi

#Determine the name of the output file and a temporary output file.
fname=$LOGS/transfer_failed.txt
temp_fname=/tmp/transfer_failed.txt
temp_vol_fname=/tmp/log_trans_fail_vol
temp_drv_fname=/tmp/log_trans_fail_drv

cd $LOGS
if [ $? -eq 1 ]
then
  # The specified log directory does not exist.
  echo "Log directory not accessible."  > /dev/null 2>&1
  return 1
fi

#Purge any temporary processing files left around.
rm -f $temp_vol_fname
rm -f $temp_drv_fname
rm -f $temp_fname

keep_recent_cached_info()
{
  cached_file="$1"
  temp_file="$2"  

  cat "$cached_file" | 
  while read line; do
     time=`echo $line | cut -f 4 -d " "`
     year=`echo "$time" | cut -f 1 -d "-"`
     month=`echo "$time" | cut -f 2 -d "-"`
     
     lastYear=`expr $thisYear - 1`
     lastMonth=`expr $thisMonth - 1`
     if [ $lastMonth -eq 0 ]; then lastMonth=12; fi

     #Skip really old errors.
     if [ $year -lt $lastYear ]; then
        continue
     elif [ $year -eq $lastYear -a $thisMonth -ge 2 ]; then
	continue
     elif [ $year -eq $thisYear -a $thisMonth -gt $month ]; then
	continue
     fi
     echo $line >> "$temp_file"
  done
}

#Loop over all the cached items.
# First for the volume sorted information.
keep_recent_cached_info "$LOGS/log_trans_fail_vol" "$temp_vol_fname"
# Second for the drive storted information.
keep_recent_cached_info "$LOGS/log_trans_fail_drv" "$temp_drv_fname"

#Create the temporary files or update the times as necessary...
# ...for volume info...
remake_cached_info=0
if [ ! -f $LOGS/log_trans_fail_vol ]; then
  touch $temp_vol_fname
  remake_cached_info=1
else
  touch -r $LOGS/log_trans_fail_vol $temp_vol_fname
fi
# ...and for or drive info.
if [ ! $LOGS/log_trans_fail_drv ]; then
  touch $temp_drv_fname
  remake_cached_info=1
else
  touch -r $LOGS/log_trans_fail_drv $temp_drv_fname
fi

#Loop over all the log files.
logfiles=`ls -1 LOG-*`
for log in $logfiles; do

  skip=0
  if [ $temp_vol_fname -nt $log ]; then skip=1; fi
  if [ $remake_cached_info -eq 1 ]; then skip=0; fi
  if [ $skip -eq 1 ]; then continue; fi

  egrep "transfer.failed|SYSLOG.Entry" $log |
  while read line; do
     echo $line | grep SYSLOG > /dev/null 2>&1
     if [ $? -eq 0 ]; then
	#What to look for if this was a "SYSLOG Entry" line.
	location="N/A"
     else
	#What to look for if this was a "transfer failed" line.
	location=`echo "$line" | sed -n 's/.*\(location=[0-9]*\) *.*/\1/p' | cut -c 10-`
	if [ -z "$location" ]; then
	    location="N/A"
	fi
     fi
     #Pull out the volume name.  The first pattern matches tape labels.  The
     # second pattern should match disk mover labels.
     volume=`echo "$line" | sed -n -e 's/.*\([A-Z]\{1\}[A-Z0-9]\{4\}[0-9]\{1\}L\{0,1\}[12]\{0,1\}\).*/\1/p' -e 's/.*\([a-z.]+:[a-zA-Z0-9_/]+\.[a-zA-Z0-9_/]+\.[a-zA-Z0-9_/]+:[0-9]*\).*/\1/p'`
     if [ -z "$volume" ]; then
	volume="N/A"
     fi
     #Other items of interest.
     time=`echo $log | cut -c 5-`:`echo "$line" | awk '{print $1}'`
     node=`echo "$line" | awk '{print $2}'`
     drive=`echo "$line" | awk '{print $6}'`
     reason=`echo "$line" | tr -s " " " " | cut -d " " -f 7-`

     year=`echo "$time" | cut -f 1 -d "-"`
     month=`echo "$time" | cut -f 2 -d "-"`
     last_year=`expr $year - 1`
     last_month=`expr $month - 1`
     if [ $last_month -eq 0 ]; then last_month=12; fi

     #Skip really old errors.
     if [ $year -lt $last_year ]; then
        continue
     elif [ $year -eq $last_year -a $thisMonth -ge 2 ]; then
	continue
     elif [ $year -eq $thisYear -a $thisMonth -gt $month ]; then
	continue
     fi
     
     #Send preprocessed output to two different places.
     echo $volume "$location" "$drive" "$time" "$reason" >> $temp_vol_fname
     echo $drive "$location" "$volume" "$time" "$reason" >> $temp_drv_fname

     #echo "volume:   " $volume
     #echo "time:     " $time
     #echo "drive:    " $drive
     #echo "location: " $location
     #echo "node:     " $node
     #echo "reason:   " "$reason"
   done

done

output_format()
{
   fname=$1
   old_part1=''

   #Make sure to remove duplicates (sort | uniq).
   cat $fname | sort | uniq |
   while read line; do
      part1=`echo "$line" | cut -f 1 -d " "`
      if [ "$part1" != "$old_part1" ]; then
         #Only print part 1 if it is different that the previous line.
         echo $part1
         old_part1=$part1
      fi

      part2=`echo "$line" | cut -f 2 -d " "`
      part3=`echo "$line" | cut -f 3 -d " "`
      part4=`echo "$line" | cut -f 4 -d " "`
      part5=`echo "$line" | cut -f 5- -d " "`
      printf "    %-9s %-12s %-22s %s\n" "$part2" "$part3" "$part4" "$part5"
   done
}

#Make sure we know how up-to-date this is.
echo -e Failed Transfers Report: `date` >> $temp_fname 2>&1
echo -e Brought to You by: `basename $0` "\n" >> $temp_fname 2>&1
#Include a header for each column.
printf "\n%s\n    %-9s %-12s %-22s %s\n" volume location drive time reason >> $temp_fname 2>&1
#Output the format sorted by volume.
output_format /tmp/log_trans_fail_vol >> $temp_fname 2>&1
#Dashed seperator.
printf "\n%80s\n" " " | tr " " "-" >> $temp_fname 2>&1 #dashed seperator.
#Repeat a header for each column.
printf "\n%s\n    %-9s %-12s %-22s %s\n" drive location volume time reason >> $temp_fname 2>&1
#
output_format /tmp/log_trans_fail_drv >> $temp_fname 2>&1

#Store these files in the log dir.  They will be used again the next time
# the script is run.
mv $temp_vol_fname $LOGS
mv $temp_drv_fname $LOGS

hostname=`hostname`
#Determine what the service IP address is for the given alias.  This
# line is fairly complicated becuase it handles nslookup output on
# Linux and SunOS (and MacOS X?).
service_ips=`nslookup $hostname | grep -i Address | sed '1d' | cut -f 2- -d " " | tr ',' "\n" | sed 's/ //g'`
#If there are more than one, pick one.
#service_ip=`echo "$service_ips" | head -n 1`

#Determine what the WEB_SERVER address is for the given alias.  This
# line is fairly complicated becuase it handles nslookup output on
# Linux and SunOS (and MacOS X?).
web_server_ips=`nslookup $WEB_SERVER | grep -i Address | sed '1d' | cut -f 2- -d " " | tr ',' "\n" | sed 's/ //g'`
web_server_ip=`echo "$web_server_ips" | head -n 1`

#If $web_server_ip is in the list of "$service_ips", we are on the same node.
echo "$service_ips" | grep $web_server_ip > /dev/null
if [ $? -eq 0 ]; then
   # We are on the same node.
   cp -p $temp_fname $HTML_DIR
else
   # We are not on the same node.
   enrcp $temp_fname $WEB_SERVER:$HTML_DIR
fi

exit $?
