#!/bin/sh
####################################################################################
#  Title : sas_depot_check.sh 
#  Product: SAS Software Depot Check Utility
#  Release Date: SEP09
#
#  Description: This script will check the SAS file distribution lists and verify the existence 
#               of the actual files and also verify the correct ownerships 
#               and permissions.  This script will also modify the $sasdir/cd.id file if
#               any volsers are missing from that file.
#
#  Output: This script will create two output files in the current directory.
#           1) sas_depot_check.out  :  Listing of all files that have a problem with 
#                                  permission, ownership or missing. 
#           2) sas_depot_check.sh.update : A script file with UNIX commands to fix 
#                                     the permission or ownership problem. 
#                                     Execute the "sas_depot_check.update" to 
#                                     fix these problems.
#
#  Usage : ./sas_depot_check.sh -d sasdirectory -o outputdirectory
#           -i     The directory of the SAS Software Depot
#           -o     The directory where output files will be written
#
#  Note1: For best results you should run this script with the same userid that
#         was used to download the SAS Software Depot.
#####################################################################################
# The following options can be adjusted within this script if necessary:
# misscount:
#   Set misscount to the number of missing files to be found before ending the script. 
#   If x number of missing files are found then there really is no reason to continue checking
#   all the files in the SAS Software Depot.  It is clear a fresh copy or download is required. 
#   If you want all files in the depot checked then set this to 9000 or any super high number.
#   misscount=10 is recommended
#####################################################################################
misscount=50
#####################################################################################
# mydebug:
#   mydebug=1 to limit the processing for testing purposes
#   mydebug=0 to run the whole script as it would normally <---recommended
####################################################################################
mydebug=0
####################################################################################
# mydebugcount:
#   If mydebug=1 then set mydebugcount to the number of files to process before we exit
#   If mydebug=0 then mydebugcount is ignored
#####################################################################################
mydebugcount=40
myversion="4.3"
####################################################################################
# mytimecheck:
#   If mytimecheck=1 then we will also validate timestamps on the files
#   If mytimecheck=0 then no validation of timestamps will take place
# We are turning off timestamp validation due to localization 
#####################################################################################
mytimecheck=0

set -f
firstcall=1
###############################
# Describe our usage parameters
###############################
usage(){
  $ECHO "\nsas_depot_check.sh version $myversion \n\n"
  $ECHO "USAGE:\t$1 -i SASDirectory -o outputDirectory\n"          
  $ECHO "-i   the directory of the SAS Software Depot (required)\n"
  $ECHO "-o   the directory where this script will create output files (required)\n"
  $ECHO "NOTE: This script should be executed with the same userid that downloaded the SAS Software Depot.\n"
}

###################
# Log missing files
###################
bad_file_write() {
  $ECHO "   $1" >> $outdir/bad_file.$$
  bad_file_index=`expr $bad_file_index + 1`
  if [ $bad_file_index -ge $misscount ]; then
    $ECHO "   A new copy or download is required.  Missing files have exceeded $misscount.  No more files will be checked." >> $outdir/bad_file.$$
    cleanup
    exit 1
  fi  
}

###################
# Log found files
###################
found_file_write() {
  $ECHO "   $1" >> $outdir/found_file.$$
  found_file_index=`expr $found_file_index + 1` 
}

###################
# Log empty files
###################
#bad_empty_write() {
  #$ECHO "   $1" >> $outdir/bad_empty.$$
  #bad_empty_index=`expr $bad_empty_index + 1`
  #if [ $bad_empty_index -ge $misscount ]; then
  #  $ECHO "   A new copy or download is required.  Empty files have exceeded $misscount.  No more files will be checked." >> $outdir/bad_empty.$$
  #  cleanup
  #  exit 1
  #fi  
#}
###################
# Log bad size files
###################
bad_size_write() {
  $ECHO "   $1" >> $outdir/bad_size.$$
  bad_size_index=`expr $bad_size_index + 1`
  if [ $bad_size_index -ge $misscount ]; then
    $ECHO "   A new copy or download is required.  Files with wrong size have exceeded $misscount.  No more files will be checked." >> $outdir/bad_size.$$
    cleanup
    exit 1
  fi 
}
###################
# Log bad time files
###################
bad_time_write() {
  $ECHO "   $1" >> $outdir/bad_time.$$
  bad_time_index=`expr $bad_time_index + 1`
}
###################
# Log bad checksum files
###################
bad_checksum_write() {
  $ECHO "   $1" >> $outdir/bad_checksum.$$
  bad_checksum_index=`expr $bad_checksum_index + 1`
  if [ $bad_checksum_index -ge $misscount ]; then
    $ECHO "   A new copy or download is required.  Files with wrong checksum have exceeded $misscount.  No more files will be checked." >> $outdir/bad_checksum.$$
    cleanup
    exit 1
  fi 
}
###################
# Log bad owner files
###################
bad_owner_write() {
  $ECHO "   $1" >> $outdir/bad_owner.$$
  bad_owner_index=`expr $bad_owner_index + 1`
}
###################
# Log bad group files
###################
bad_group_write() {
  $ECHO "   $1" >> $outdir/bad_group.$$
  bad_group_index=`expr $bad_group_index + 1`
}
###################
# Log cdid changes
###################
bad_cdid_write() {
  $ECHO "   $1" >> $outdir/bad_cdid.$$
  bad_cdid_index=`expr $bad_cdid_index + 1`
}
###################
# Log bad permission files
###################
bad_permission_write() {
  $ECHO "   $1" >> $outdir/bad_permission.$$
  bad_permission_index=`expr $bad_permission_index + 1`
}

#######################
# Check files on disk #
#######################
files_on_disk() {
  checkall=0
  goodsize=0
  mysize=""
  mytime=""
  mychecksum=""
  file="$1"
  checkall=$2
  if [ $checkall -eq 1 ]; then
    mysize="$3"
    mytime="$4"
    mychecksum="$5"
  fi
  if [ $firstcall -eq 1 ]; then
    flcount=0
  fi  
  flcount=`expr $flcount + 1`
  $ECHO "Now checking $flcount : $file"
  exist=1

  ## Checking that all files exist 
  if [ ! -r "$file" ];then
    bad_file_write "$file"
    exist=0
  else
    found_file_write "$file"
    
    # $1=permissions
    # $3=owner
    # $4=group
    # $5=length
    # $6=month
    # $7=day
    # $8=year or time   
    # HPUX and AIX provide no timestamp formatting options on the ls command so we have get it the hard way
    if [ $osname = "HP-UX" -o $osname = "AIX" -o $osname = "SunOS" ]; then
  
      filestuff=`$ECHO "$file" | cpio -o 2>/dev/null | cpio -ivt 2>/dev/null | awk '{print $3 " " $4 " " $5 " " $6 }'`   
      tempmonth=`$ECHO "$filestuff" | $AWK '{print $1}'`       
      case "$tempmonth" in
        Jan) tempmonth="01" ;;
	Feb) tempmonth="02" ;;
	Mar) tempmonth="03" ;;
	Apr) tempmonth="04" ;;
	May) tempmonth="05" ;;
	Jun) tempmonth="06" ;;
	Jul) tempmonth="07" ;;
	Aug) tempmonth="08" ;;
	Sep) tempmonth="09" ;;
	Oct) tempmonth="10" ;;
	Nov) tempmonth="11" ;;
	Dec) tempmonth="12" ;;
	*) tempmonth="00" ;;
      esac    
      if [ $tempmonth = "00" ]; then
	filestuff=`$ECHO "$file" | cpio -o 2>/dev/null | cpio -ivt 2>/dev/null | awk '{print $4 " " $5 " " $6 " " $7}'`   
	tempmonth=`$ECHO "$filestuff" | $AWK '{print $1}'`       
	case "$tempmonth" in
          Jan) tempmonth="01" ;;
	  Feb) tempmonth="02" ;;
	  Mar) tempmonth="03" ;;
	  Apr) tempmonth="04" ;;
	  May) tempmonth="05" ;;
	  Jun) tempmonth="06" ;;
	  Jul) tempmonth="07" ;;
	  Aug) tempmonth="08" ;;
	  Sep) tempmonth="09" ;;
	  Oct) tempmonth="10" ;;
	  Nov) tempmonth="11" ;;
	  Dec) tempmonth="12" ;;
	  *) tempmonth="00" ;;
	esac       
      fi
             
      tempyear=`$ECHO "$filestuff" | $AWK '{print $4}'`     
      tempday=`$ECHO "$filestuff" | $AWK '{print $2}'`    
      if [ $osname = "HP-UX" -a $tempday -lt 10 ]; then
	tempday=0$tempday
      fi 
      calctime=temptime       
      temptime=`$ECHO "$filestuff" | $AWK '{print $3}' | sed 's/://g'` 
      real_time="$tempyear$tempmonth$tempday$temptime"	 
      filestuff=`ls -ld "$file" | $AWK '{print $1 " " $2 " " $3 " " $4 " " $5 " " $6 }'`          
    else
      # Get the timestamp using time-style options for all other Unix flavors
      filestuff=`ls -ld --time-style=+%Y%m%d%H%M%S "$file" | $AWK '{print $1 " " $2 " " $3 " " $4 " " $5 " " $6 }'`   
      real_time=`$ECHO "$filestuff" | $AWK '{print $6}'`              
    fi

    filemode=`$ECHO "$filestuff" | $AWK '{print $1}' | sed 's/^d/-/'`    
    real_owner=`$ECHO "$filestuff" | $AWK '{print $3}'`
    real_group=`$ECHO "$filestuff" | $AWK '{print $4}'`   
    real_size=`$ECHO "$filestuff" | $AWK '{print $5}'`     
    
    # Undo checking for empty files, 15JUN2010
    #length=`$ECHO "$filestuff" | $AWK '{print $5}'`

    # If this is our first pass then set the owner and group to be the standard
    # by which we compare all other files
    if [ $firstcall -eq 1 ]; then
      owner=$real_owner
      group=$real_group
      $ECHO " " > "$UPDATE_FILE"
      $ECHO " " > "$OUTPUT_FILE"
    fi   
    length=2
    if [ $length -eq 0 ]; then
      bad_empty_write "$file"
    else
      ## Check Owner
      if [ $owner != $real_owner ]; then
        bad_owner_write "$file"
	$ECHO "chown $owner \"$file\" " >> "$UPDATE_FILE"
      fi

      ## Check Group
      if [ $group != $real_group ]; then
        bad_group_write "$file "
	$ECHO "chgrp $group \"$file\" " >> "$UPDATE_FILE"
      fi
      ## Check Permission    
      real_permission=`file_mode "$file"`
      if [ 755 -gt $real_permission ];then
        bad_permission_write "$file"
	$ECHO "chmod 755 \"$file\" " >> "$UPDATE_FILE"
      fi   
      if [ $checkall -eq 1 ]; then        
        ## Check Size if we were given a size	
        if [ -n "$mysize" -a $depotversion -gt 0 ]; then
	  goodsize=1	  
	  if [ $mysize -ne $real_size ]; then
	    goodsize=0
	    bad_size_write "$file Expected:$mysize Actual:$real_size"
	  fi
	fi  
        ## Check time if we were given a time and mytimecheck is turned on
        if [ $mytimecheck -eq 1 -a "$mytime" != "" -a "$mytime" != " " -a "$mytime" != "$real_time" ]; then 	
	  ## Break apart real_time then add and subtract 1 second then compare again
	  getdates "$real_time"
	  if [ "$mytime" != "$pretime" -a "$mytime" != "$posttime" ]; then
	    bad_time_write "$file"	    	        
	  fi

	fi  	      
        ## Check checksum if we were given a checksum and the size checked out ok	
        ##if [ $dochecksum -eq 1 -a "$mychecksum" != "" -a "$mychecksum" != " " -a $goodsize -eq 1 ]; then
	  if [ $dochecksum -eq 1 -a "$mychecksum" != "" -a "$mychecksum" != " " ]; then
	    real_checksum=`$checksumgenerator $file | $AWK '{print $1}'`	  
	  if [ "$mychecksum" != "$real_checksum" ]; then
	    bad_checksum_write "$file Expected:$mychecksum Actual:$real_checksum"
	  fi
	fi       
      fi
    fi
  fi 
  #If we are testing, limit the files processed and exit early
  if [ $mydebug -eq 1 -a $flcount -ge $mydebugcount ]; then
    cleanup
    exit 1
  fi  
}

##############################
# File Permission Definition #
##############################
file_mode(){
$ECHO $filemode | $AWK '{
  c1=substr($1,1,1)
  c2=substr($1,2,1)
  c3=substr($1,3,1)
  c4=substr($1,4,1)
  c5=substr($1,5,1)
  c6=substr($1,6,1)
  c7=substr($1,7,1)
  c8=substr($1,8,1)
  c9=substr($1,9,1)
  c0=substr($1,10,1)

  up=0
  gp=0
  op=0
  sp=0

  if (c2=="r") {up+=4}
  if (c3=="w") {up+=2}
  if (c4=="x") {up+=1}
  if (c4=="s" || c4=="S") {sp+=4
		up+=1}
  if (c5=="r") {gp+=4}
  if (c6=="w") {gp+=2}
  if (c7=="x") {gp+=1}
  if (c7=="s" || c7=="S") {sp+=2
		gp+=1}
  if (c8=="r") {op+=4}
  if (c9=="w") {op+=2}
  if (c0=="x") {op+=1}
  if (c0=="t" || c0=="T") {sp+=1
		op+=1}
  printf("%1d%1d%1d%1d\n", sp, up, gp, op) }'
}

################################################################
# Create one second before and one second after datetime stamps
###############################################################
getdates() {
  real_time=$1
  ayear=`expr substr "$real_time" 1 4`
  amonth=`expr substr "$real_time" 5 2`
  aday=`expr substr "$real_time" 7 2`
  ahour=`expr substr "$real_time" 9 2`
  aminute=`expr substr "$real_time" 11 2`
  asecond=`expr substr "$real_time" 13 2`
  postyear=$ayear
  postmonth=$amonth
  preyear=$ayear
  premonth=$amonth
  if [ $asecond = "00" ]; then
    if [ $aminute = "00" ]; then
      if [ $ahour = "00" ]; then
	preday=`expr $aday - 1`
	prehour='59'
	premin='59'
	presec='59'
	postday=$aday
	posthour=$ahour
	postmin=$aminute
	postsec=`expr $asecond + 1`
	if [ $postsec -lt 10 ]; then
	  postsec=0$postsec
	fi
	if [ $amonth = "01" -a $preday -lt 1 ]; then
	  preday="31"
	  premonth="12"
	  preyear=`expr $ayear - 1`
	elif [ $amonth = "02" -a $preday -lt 1 ]; then
	  preday="31"
	  premonth="01"  
	elif [ $amonth = "03" -a $preday -lt 1 ]; then
	  preday="28"
	  premonth="02" 		  
	elif [ $amonth = "04" -a $preday -lt 1 ]; then
	  preday="31"
	  premonth="03" 		  
	elif [ $amonth = "05" -a $preday -lt 1 ]; then
	  preday="30"
	  premonth="04" 		  
	elif [ $amonth = "06" -a $preday -lt 1 ]; then
	  preday="31"
	  premonth="05" 		  
	elif [ $amonth = "07" -a $preday -lt 1 ]; then
	  preday="30"
	  premonth="06" 
	elif [ $amonth = "08" -a $preday -lt 1 ]; then
	  preday="31"
	  premonth="07"		  
	elif [ $amonth = "09" -a $preday -lt 1 ]; then
	  preday="31"
	  premonth="08"		  
	elif [ $amonth = "10" -a $preday -lt 1 ]; then
	  preday="30"
	  premonth="09"		  
	elif [ $amonth = "11" -a $preday -lt 1 ]; then
	  preday="31"
	  premonth="10"		  
	elif [ $amonth = "12" -a $preday -lt 1 ]; then
	  preday="30"
	  premonth="11"		  		  
	fi	      	      
      else
	preday=$aday
	prehour=`expr $ahour - 1`
	premin='59'
	presec='59'
	postday=$aday
	posthour=$ahour
	postmin=$aminute
	postsec=`expr $asecond + 1`
	if [ $postsec -lt 10 ]; then
	  postsec=0$postsec
	fi
	if [ $prehour -lt 10 ]; then
	  prehour=0$prehour
	fi	      
      fi
    else  
      preday=$aday
      prehour=$ahour
      premin=`expr $aminute - 1`
      presec="59"
      postday=$aday
      posthour=$ahour
      postmin=$aminute
      postsec="01"
      if [ $premin -lt 10 ]; then
	premin=0$premin
      fi
    fi  
  elif [ $asecond = "59" ]; then
    if [ $aminute = "59" ]; then
      if [ $ahour = "59" ]; then
	preday=$aday
	prehour=$ahour
	premin=$aminute
	presec=`expr $asecond - 1`
	postday=`expr $aday + 1`
	posthour="00"
	postmin="00"
	postsec="00"
	if [ $postday -lt 10 ]; then
	  postday=0$postday
	fi
	if [ $presec -lt 10 ]; then
	  presec=0$presec
	fi
	if [ $amonth = "01" -a $postday -gt 31 ]; then
	  postday="01"
	  postmonth="02"
	elif [ $amonth = "02" -a $postday -gt 28 ]; then
	  postday="01"
	  postmonth="03"  
	elif [ $amonth = "03" -a $postday -gt 31 ]; then
	  postday="01"
	  postmonth="04" 		  
	elif [ $amonth = "04" -a $postday -gt 30 ]; then
	  postday="01"
	  postmonth="05" 		  
	elif [ $amonth = "05" -a $postday -gt 31 ]; then
	  postday="01"
	  postmonth="06" 		  
	elif [ $amonth = "06" -a $postday -gt 30 ]; then
	  postday="01"
	  postmonth="07" 		  
	elif [ $amonth = "07" -a $postday -gt 31 ]; then
	  postday="01"
	  postmonth="08" 
	elif [ $amonth = "08" -a $postday -gt 31 ]; then
	  postday="01"
	  postmonth="09"		  
	elif [ $amonth = "09" -a $postday -gt 30 ]; then
	  postday="01"
	  postmonth="10"		  
	elif [ $amonth = "10" -a $postday -gt 31 ]; then
	  postday="01"
	  postmonth="11"		  
	elif [ $amonth = "11" -a $postday -gt 30 ]; then
	  postday="01"
	  postmonth="12"		  
	elif [ $amonth = "12" -a $postday -gt 31 ]; then
	  postday="01"
	  postmonth="01"		  
	  postyear=`expr $ayear + 1`		  
	fi	      
      else
	preday=$aday
	prehour=$ahour
	premin=$aminute
	presec=`expr $asecond - 1`
	postday=$aday
	posthour=`expr $ahour + 1`
	postmin=00
	postsec=00
	if [ $posthour -lt 10 ]; then
	  posthour=0$posthour
	fi
	if [ $presec -lt 10 ]; then
	  presec=0$presec
	fi			      
      fi	    	    
    else
      preday=$aday
      prehour=$ahour
      premin=$aminute
      presec="58"
      postday=$aday
      posthour=$ahour
      postmin=`expr $aminute + 1`
      postsec="00"
      if [ $postmin -lt 10 ]; then
	  postmin=0$postmin
      fi
    fi	    
  else
    preday=$aday
    postday=$aday
    prehour=$ahour
    posthour=$ahour
    premin=$aminute
    presec=`expr $asecond - 1`
    postmin=$aminute
    postsec=`expr $asecond + 1`
    if [ $postsec -lt 10 ]; then
      postsec=0$postsec
    fi
    if [ $presec -lt 10 ]; then
      presec=0$presec
    fi
  fi	

  posttime=$postyear$postmonth$postday$posthour$postmin$postsec
  pretime=$preyear$premonth$preday$prehour$premin$presec
  
}

############################################
# Update the output files to log our results
# and clean up stuff
############################################
cleanup(){
  $ECHO "  SAS Software Depot Check Utility version $myversion" > "$OUTPUT_FILE"
  
  ### Did we do checksum checking? ###
  if [ $dochecksum -eq 0 ]; then
    $ECHO "\n Checksum validation has been turned off." >> "$OUTPUT_FILE"
    $ECHO "   Either md5sum or csum must be in your PATH for checksum validation to work." >> "$OUTPUT_FILE"
    $ECHO "   See the tech support notes for requirements for sas_depot_check.sh. " >> "$OUTPUT_FILE"
  fi
  
  ### Log the missing files ###
  $ECHO "\n Missing File(s)" >> "$OUTPUT_FILE"  
  if [ $bad_file_index -eq 0 ]; then
    $ECHO "   No files are missing." >> "$OUTPUT_FILE"
  else  
    $ECHO "   A FRESH DOWNLOAD IS RECOMMENDED.  Missing files are an indication of an incomplete download." >> "$OUTPUT_FILE"
    cat "$outdir/bad_file.$$" >> "$OUTPUT_FILE"
  fi
  
  ### Log the found files ###
  if [ $found_file_index -ne 0 -a $verbose -eq 1 ]; then
    $ECHO "Found Files: " >> "$OUTPUT_FILE"
    cat "$outdir/found_file.$$" >> "$OUTPUT_FILE"
  fi  
  
  ### Log the empty files ###
  #$ECHO "\n Empty File(s)" >> "$OUTPUT_FILE"
  #if [ $bad_empty_index -eq 0 ]; then
  #  $ECHO "   No empty files were found." >> "$OUTPUT_FILE"
  #else  
  #  cat "$outdir/bad_empty.$$" >> "$OUTPUT_FILE"
  #fi  

  
  ### Log the files with wrong size ###
  $ECHO "\n Wrong Size File(s) " >> "$OUTPUT_FILE"
  if [ $bad_size_index -eq 0 ]; then
    $ECHO "   All files had the correct size." >> "$OUTPUT_FILE"
  else  
    $ECHO "   A FRESH DOWNLOAD IS RECOMMENDED.  Wrong size files are an indication of an incomplete download." >> "$OUTPUT_FILE"
    cat "$outdir/bad_size.$$" >> "$OUTPUT_FILE"
  fi 

  ### Log the files with wrong time ###
  if [ $mytimecheck -eq 1 ]; then
    $ECHO "\n Wrong Time Stamp File(s) " >> "$OUTPUT_FILE"
    if [ $bad_time_index -eq 0 ]; then
      $ECHO "   All files had the correct timestamp." >> "$OUTPUT_FILE"
    else  
      cat "$outdir/bad_time.$$" >> "$OUTPUT_FILE"
    fi 
  fi

  ### Log the files with wrong checksum ###
  if [ $dochecksum -eq 1 ]; then
    $ECHO "\n Wrong Checksum File(s) " >> "$OUTPUT_FILE"
    if [ $bad_checksum_index -eq 0 ]; then
      $ECHO "   All files had the correct checksum." >> "$OUTPUT_FILE"
    else  
      $ECHO "   A FRESH DOWNLOAD IS RECOMMENDED.  Wrong checksums are an indication of an incomplete download." >> "$OUTPUT_FILE"
      cat "$outdir/bad_checksum.$$" >> "$OUTPUT_FILE"
    fi 
  fi
        
  ### Log the files with wrong owners ###
  $ECHO "\n Wrong Owner File(s) (Execute $UPDATE_FILE for fix)" >> "$OUTPUT_FILE"
  if [ $bad_owner_index -eq 0 ]; then
    $ECHO "   All files had the correct owner." >> "$OUTPUT_FILE"
  else  
    cat "$outdir/bad_owner.$$" >> "$OUTPUT_FILE"
  fi  

  ### Log the files with wrong group ###
  $ECHO "\n Wrong Group File(s) (Execute $UPDATE_FILE for fix)" >> "$OUTPUT_FILE"
  if [ $bad_group_index -eq 0 ]; then
    $ECHO "   All files had the correct group." >> "$OUTPUT_FILE"
  else  
    cat "$outdir/bad_group.$$" >> "$OUTPUT_FILE"
  fi
  
  ### Log the files with wrong permission ###
  $ECHO "\n Wrong Permission File(s) (Execute $UPDATE_FILE for fix)" >> "$OUTPUT_FILE"
  if [ $bad_permission_index -eq 0 ]; then
    $ECHO "   All files had correct permissions." >> "$OUTPUT_FILE"
  else  
    cat "$outdir/bad_permission.$$" >> "$OUTPUT_FILE"
  fi
  
  ### Log the missing volsers in cd.id ###
  if [ $write_cdid -eq 0 -a $bad_cdid_index -gt 0 ]; then
    $ECHO "\n Attempted update to cd.id failed.  Check permissions." >> "$OUTPUT_FILE"
    $ECHO "\n Attempted to add these missing volsers to cd.id: " >> "$OUTPUT_FILE"
    cat "$outdir/bad_cdid.$$" >> "$OUTPUT_FILE"
  else  
    $ECHO "\n Missing volsers in cd.id that have been corrected" >> "$OUTPUT_FILE"
    if [ $bad_cdid_index -eq 0 ]; then
      $ECHO "   All volsers were listed in cd.id." >> "$OUTPUT_FILE"
    else  
      cat "$outdir/bad_cdid.$$" >> "$OUTPUT_FILE"
    fi    
  fi
  if [ -r "$outdir/volsers.$$" ]; then
    rm "$outdir/volsers.$$"
  fi
  if [ -r "$outdir/altskus.$$" ]; then
    rm "$outdir/altskus.$$"
  fi
  if [ -r "$outdir/orders.$$" ]; then
    rm "$outdir/orders.$$"
  fi
  if [ -r "$outdir/bad_file.$$" ]; then
    rm "$outdir/bad_file.$$"
  fi
  if [ -r "$outdir/found_file.$$" ]; then
    rm "$outdir/found_file.$$"
  fi  
  #if [ -r "$outdir/bad_empty.$$" ]; then
  #  rm "$outdir/bad_empty.$$"
  #fi
  if [ -r "$outdir/bad_size.$$" ]; then
    rm "$outdir/bad_size.$$"
  fi
  if [ -r "$outdir/bad_time.$$" ]; then
    rm "$outdir/bad_time.$$"
  fi  
  if [ -r "$outdir/bad_checksum.$$" ]; then
    rm "$outdir/bad_checksum.$$"
  fi  
  if [ -r "$outdir/bad_group.$$" ]; then
    rm "$outdir/bad_group.$$"
  fi
  if [ -r "$outdir/bad_owner.$$" ]; then
    rm "$outdir/bad_owner.$$"
  fi
  if [ -r "$outdir/bad_permission.$$" ]; then
    rm "$outdir/bad_permission.$$"
  fi      
  if [ -r "$outdir/bad_cdid.$$" ]; then
    rm "$outdir/bad_cdid.$$"
  fi
    
  # Provide some informative messages
  $ECHO "\nProcessing Complete.  $flcount files have been checked."
  $ECHO "See the following files for results:"
  $ECHO "$OUTPUT_FILE"
  $ECHO "$UPDATE_FILE"
  exit 1
}

################
# Main Program #
################
osname=`uname -s`
if [ $osname = "SunOS" ]; then
  AWK=nawk
else
  AWK=awk
fi

if [  $osname = "Linux" ]; then
  ECHO='echo -e'
else
  ECHO=echo
fi

###############################
# Initialize output lists
###############################
bad_file_index=0
found_file_index=0
#bad_empty_index=0
bad_size_index=0
bad_time_index=0
bad_checksum_index=0
bad_owner_index=0
bad_group_index=0
bad_cdid_index=0
bad_permission_index=0
write_cdid=1
depotversion=0
verbose=0

############################
# Parse the input parameters
############################
set -- `getopt i:o:v: "$*"`
if [ $? -ne 0 ];then
  usage `basename $0`
  exit 2
fi
  
if [ $1 != "-i" ] && [ $1 != "-o" ]; then
  usage `basename $0`
  exit 2
fi

myparm=0
sasdir=""
outdir=""
for i in $*
do
  if [ "$i" = "-i" ]; then
    myparm=1
  elif [ "$i" = "-o" ]; then
    myparm=2
  elif [ "$i" = "-v" ]; then
    myparm=3  
  fi
  if [ $myparm -eq 1 -a "$i" != "-i" -a "$i" != "-v" -a "$i" != "--" ]; then
    sasdir=`$ECHO $sasdir $i`
  elif [ $myparm -eq 2 -a "$i" != "-o" -a "$i" != "-v" -a "$i" != "--" ]; then
    outdir=`$ECHO $outdir $i` 
  elif [ $myparm -eq 3 -a "$i" != "-i" -a "$i" != "-o" -a "$i" != "--" ]; then
    verbose=1     
  fi    
done

##########################################
# Do some checking on the parameter values
##########################################
if [ ! -d "$sasdir" ];then
  $ECHO "Invalid SAS Depot Directory: $sasdir"
  exit 2
fi
if [ ! -d "$outdir" ];then
  $ECHO "Invalid Output Directory: $outdir"
  exit 2
fi

#############################
# Initialize our output files
#############################
OUTPUT_FILE="$outdir/sas_depot_check.out"
UPDATE_FILE="$outdir/sas_depot_check.update"

##############################################################################################
# Fine the md5 checksum generator, turn of checksum validation if we don't find md5sum or csum
##############################################################################################
dochecksum=1
checksumgenerator=`which md5sum`
nochecksumgenerator=`which md5sum | grep -ic 'no md5sum'`
if [ $nochecksumgenerator -gt 0 -o "$checksumgenerator" = "" -o "$checksumgenerator" = " " ]; then
  checksumgenerator=`which csum`
  nochecksumgenerator=`which csum | grep -ic 'no csum'`  
  if [ $nochecksumgenerator -gt 0 -o "$checksumgenerator" = "" -o "$checksumgenerator" = " " ]; then
    dochecksum=0
  fi
fi

#########################################
# Begin processing with the order numbers
#########################################
ls -A "$sasdir/order_data"/ > "$outdir/orders.$$"
for order in `cat "$outdir/orders.$$"`
do
  ##########################################
  # First we loop through the order numbers
  ##########################################
  # Check that order.xml exists in the order directory 
  orderxml="$sasdir/order_data/$order/order.xml"
  files_on_disk "$orderxml" 0
  firstcall=0
  if [ $exist -eq 0 ];then
    bad_file_write "$orderxml"
    cleanup 
  else
    if [ $length -eq 0 ]; then
      cleanup
      exit 1
    else
      ############################################################################	
      # Second, we loop through the volsers from order.xml for each order number
      # Start by getting the mediatype
      ############################################################################     
      depotversion=`grep -ic 'depot_version="2"' "$orderxml"`      
      esdm=`grep -ic 'mediatype="ESDM"' "$orderxml"`
      dvdm=`grep -ic 'mediatype="DVDM"' "$orderxml"`
      cdrm=`grep -ic 'mediatype="CDRM"' "$orderxml"`
      esdm=`grep -ic 'mediatype="ESDM"' "$orderxml"`	
      # Get the filenames for the appropriate mediatype;
      if [ $esdm -gt 0 ]; then
        grep -i _es "$orderxml" | grep -in volser | $AWK -F\" '{print $2}' > "$outdir/volsers.$$"
      elif [ $dvdm -gt 0 ]; then
        grep -i _ds "$orderxml" | grep -in volser | $AWK -F\" '{print $2}' > "$outdir/volsers.$$"
      elif [ $cdrm -gt 0 ]; then
        grep -i _cd "$orderxml" | grep -in volser | $AWK -F\" '{print $2}' > "$outdir/volsers.$$"
      else
        $ECHO "\n$orderxml file is corrupt.  Recopy or redownload the SAS Software Depot."
        cleanup
        exit 1
      fi 
      # Read the $sasdir/media_data/$volser.xml file for each volser
      for volser in `cat "$outdir/volsers.$$"`
      do
        #######################################################
        # Third, we read the altsku and pkgpath for each volser
        # We also check the cd.id file to be sure it has one line
        # for each volser.
        ####################################################### 
        ## Check the cd.id file, if our volser does not exist, add it
        files_on_disk "$sasdir/cd.id" 0
        if [ $exist -eq 1 ]; then
          foundit=`grep -c $volser "$sasdir/cd.id" | $AWK -F\t '{print $1}'`
          if [ $foundit -eq 0 ]; then
            $ECHO "$volser" >> "$sasdir/cd.id"
	    if [ $? -ne 0 ]; then
	      write_cdid=0
	    fi  
            bad_cdid_write $volser 	    
          fi
        fi
        volserxml="$sasdir/media_data/$volser.xml"
        if [ ! -r "$volserxml" ];then
          bad_file_write "$volserxml"
          cleanup
          exit 1
        else
	  found_file_write "$volserxml"
          files_on_disk "$volserxml" 0   
          grep -i 'product alt_sku=' "$volserxml" | sed 's/format="standard"//g' | awk -F\" '{print $2 "---" $4}' > "$outdir/altskus.$$"   
          for myline in `cat "$outdir/altskus.$$"`
          do 
            ##############################################################################
            # Fourth, we read all the filelist.xml files to get the files we need to check
            ##############################################################################
            # Assign both $altsku and $pkgpath for the current line
            altsku=`$ECHO $myline | $AWK -F\--- '{print $1}'`
            pkgpath=`$ECHO $myline | $AWK -F\--- '{print $2}'`	
            #See if the filelist.xml file exists
            exist=1
            if [ ! -r "$sasdir/product_data/$altsku/filelist.xml" ]; then
              exist=0
            fi  
            if [ $exist -eq 1 ]; then
              skupkg=0
              skudat=0
		  
              # Set the file to stdin so we can read properly
              # Note: using 'read' caused problems with the flcount values
              exec 9<&0 < "$sasdir/product_data/$altsku/filelist.xml"
              # Now read the filelist.xml file from stdin
              while read line
              do
                myvar1=`$ECHO $line | $AWK '{print $1}'`
                myvar2=`$ECHO $line | $AWK '{print $2}'`
		myvar3=`$ECHO $line | $AWK '{print $3}'`
		myvar4=`$ECHO $line | $AWK '{print $4}'`		
		myvar5=`$ECHO $line | $AWK '{print $5}'`
                if [ $myvar1 = "<skupkg" ]; then
                  skupkg=1
                elif [ $myvar1 = "</skupkg>" ]; then
                  skupkg=0
                elif [ $myvar1 = "<skudat" ]; then
                  skudat=1
                elif [ $myvar1 = "</skudat>" ]; then
                  skudat=0   
                fi  
                if [ $myvar1 = "<file" ]; then    
                  file=`$ECHO "$myvar2" | awk -F\" '{print $2}'`
		  # Figure out if we have the new size, time and checksum info in this filelist.xml
		  size=`$ECHO "$myvar3" | awk -F\" '{print $2}'`
		  time=`$ECHO "$myvar4" | awk -F\" '{print $2}'`		  
		  checksum=`$ECHO "$myvar5" | awk -F\" '{print $2}'`	
		  ##########################################################################
		  # If the pkgpath is not blank and we are on the skupkg section, check it 
		  # otherwise check the skudat                                        
		  ##########################################################################
                  if [ $skupkg -eq 1 -a -n "$pkgpath" ]; then
		      files_on_disk "$sasdir/$pkgpath/$file" 1 $size $time $checksum
		  elif [ $skudat -eq 1 ]; then
                    files_on_disk "$sasdir/product_data/$altsku/$file" 1 $size $time $checksum 
                  fi     	 	 
                fi
              done
              exec 0<&9 9<&- 
            fi
          done    
        fi
      done        	
    fi	
  fi
done
cleanup
exit 1







