#!/bin/sh

#
# $Id: pks-queue-run.sh,v 1.4 1996/12/11 19:17:27 marc Exp $
#
# Copyright (c) 1996, Marc Horowitz.  All rights reserved.
# See the LICENSE file in the release for redistribution information.

conf="$1"

case "X$conf" in
	X)
		echo "usage: $0 conf_file" 1>&2
		exit 1
		;;
esac

[ ! -r $conf ] && {
	echo "conf_file $conf is not readable" 1>&2
	exit 1
}
		
dir=`awk '/mail_dir/ { print $2 }' < $conf`
socket=`awk '/socket_name/ { print $2 }' < $conf`
bindir=`awk '/pks_bin_dir/ { print $2 }' < $conf`
dbdir=`awk '/db_dir/ { print $2 }' < $conf`
restart=yes

counttot=0
countstart=`date`
countrestart=0
lasttried="just started"

while test 1; do 
  for file in $dir/pks-mail.*; do
      # get pksd info
      pid=`/sbin/checkproc -v $bindir/pksd`
      if test -z $pid; then 
        if test "$restart" = yes ; then 
	  if test ! -d $dir/bad ; then
            mkdir $dir/bad
          fi
	  for i in $dir/pks-mail.* ; do mv $i $dir/bad ; done
	  echo `date`: recovering... last tried file was: $lasttried
          $bindir/pksclient $dbdir recover
	  echo `date`: restarting pksd
          ( $bindir/pksd $conf & )
	  countrestart=$(($countrestart+1))
	  echo `date`: pksd started. restart counter: $countrestart
          # sleep 2; chmod g+w /opt/pks/var/pksd_socket
          # chgrp daemon /opt/pks/var/pksd_socket
        else 
          echo `date`: $bindir/pksd is not running - waiting for pksd...
	  sleep 5
        fi
        sleep 20
      else
        # get system info
        sysinfo=`awk '{print $2 "/" $1}' </proc/sys/fs/file-nr`
        procs=`awk '{print $4}' </proc/loadavg | awk -F / '{print $2}'`
	while (test $procs -gt 220) ; do 
	  echo `date`: There are $procs processes - sleeping to wait for less processes. Sysinfo: $sysinfo 
	  sleep 30
          sysinfo=`awk '{print $2 "/" $1}' </proc/sys/fs/file-nr`
   	  procs=`awk '{print $4}' </proc/loadavg | awk -F / '{print $2}'`
        done
	while (test "`ps ax | grep sendmail | grep rejecting`" != "") ; do
          echo `date`: sendmail is rejecting connections - waiting
	  sleep 30
	done    
	if [ -r "$file" ]; then
          counttot=$(($counttot+1))
          lasttried=$file
          # backlog=`echo -1`
	  backlog=`ls $dir | grep pks-mail | wc -l`
	  backlog=$(($backlog-1))
	  echo `date` $file $backlog $procs $sysinfo $counttot $countrestart $countstart
	  $bindir/pksdctl $socket "mail $file"
	  # sleep 1
	fi
      fi
  done
  sleep 1
done


