#!/bin/bash

# deletes old or corrupted files in sendfile incoming spool
# directories which are expired
# see /etc/sendfile.cf for settings

test -f /etc/sendfile.cf || exit 0
test -x /usr/bin/sendfile || exit 0
spooldir=$(sendfile -qW=spool)
cd $spooldir || exit 0
export LANG=C

maxage=$(grep '^deljunk' /etc/sendfile.cf)
test -n "$maxage" || exit 0
maxage=${maxage##*=}
maxage=${maxage/	/}
maxage=${maxage/ /}

pivot=$spooldir/pivot
touch -d now-${maxage}days $pivot
touch -d now-1day $pivot.yesterday

tmp=$(mktemp)

trap "rm -f $tmp $pivot $pivot.yesterday" INT EXIT

for i in *
do
   if [ -z "$(getent passwd "$i")" ]
   then
       continue
   fi

   echo -n > $tmp
   if [ -d "$i" ]
   then
       (
	   cd "$i"
	   for f in $(find -maxdepth 1 -name '*.h')
	   do
	     b=${f#./}
	     b=${b%.h}

	     FILE=
	     SIZE=
	     while read line
	       do
	       case $line in
		   FILE*) FILE=${line#FILE	}
		          ;;
		   SIZE*) SIZE=${line#SIZE	}
		          SIZE=${SIZE#* }
		          ;;
	       esac
	     done < $f
	     size=$(stat $b.d|grep Size)
	     size=${size#*Size: }
	     size=${size%% *}

	     if [ $SIZE -gt $size ]
	     then
		 if [ $b.d -ot $pivot ]
		 then
		     logger -i -p daemon.info -t sendfile "sf_cleanup: Expired partial file $b for user $i"
		     rm -f ${b}.{dh}
		 else
		     if [ $b.d -ot $pivot.yesterday ]
		     then
			 echo "Partial file $b will expire after $maxage days" >> $tmp
		     fi
		 fi
	     fi
	  done
      )
      if [ -s $tmp ]
      then
	  (
	      echo "Subject: Weekly SAFT Report"
	      echo "From: SAFT Server <root>"
	      echo
	      echo "The following incompletely received files have been found in the SAFT"
	      echo "spool directory $spooldir:"
	      echo
	      cat $tmp
	  ) | /usr/sbin/sendmail $i
      fi
  fi
done
