#!/bin/csh -f

set TRUE = 1
set FALSE = 0

set debug = $FALSE
set freeze = $FALSE
set verbse = $FALSE

while ($#argv >= 1)
    set flags = `expr $argv[1] : '-\(.*\)'`
    if ("$flags" == "") \
	break
    while ("$flags" != "")
	set flag = `expr $flags : '\(.\)'`
	set flags = `expr $flags : '.\(.*\)'`
	switch ($flag)
	    case "d":
		set debug = $TRUE
		breaksw
	    case "v":
		set verbse = $TRUE
		breaksw
	    case "z":
		set freeze = $TRUE
		breaksw
	    default:
		echo "unknown flag -$flag"
		exit -1
	endsw
    end
    shift
end

if ($freeze) then
    if ($debug || $verbse) \
	echo "freezing configuration file"
    if (! $debug) then
	/usr/lib/sendmail -bz
    endif
endif

# okay, try and find the sendmail daemon
#  heuristics: find all processes with the string "/usr/lib/sendmail "
#     or "(sendmail)".  Of these, find the process with the string "bd"
#     and the lowest pid, or (if no process with "bd") just the process
#     with the lowest pid.

set TMPFILE = /tmp/restart.$$

ps ax | \
    egrep '[0-9]+:[0-9]+[ ]+/usr/lib/sendmail -bd\
[0-9]+:[0-9]+[ ]+\(sendmail\)' | grep -v grep > $TMPFILE

set wordcount = `wc -l $TMPFILE`
set lines = $wordcount[1]

set i = 1
set pid = 0
set daemonfound = $FALSE

while ( $i <= $lines )
    set line = `tail +$i $TMPFILE | head -1`
    @ i++
    if ($debug || $verbse) \
	echo "sendmail process: $line"
    set daemonline = `echo "$line" | grep -e -bd`
    if ("$daemonline" != "") then
	if ($debug || $verbse) \
	    echo "found daemon sendmail: $daemonline"
	if ((! $daemonfound) || $pid == 0) then
	    if ($debug || $verbse) \
		echo "initializing pid to daemon pid $daemonline[1]"
	    set pid = $daemonline[1]
	    set daemonfound = $TRUE
	else if ($daemonline[1] < $pid)
	    if ($debug || $verbse) \
		echo "replacing pid $pid with lower daemon pid $daemonline[1]"
	    set pid = $daemonline[1]
	endif
    else if (! $daemonfound) then
	if ($pid == 0 || $line[1] < $pid) then
	    if ($debug || $verbse) \
		echo "replacing pid $pid with sendmail pid $line[1]"
	    set pid = $line[1]
	endif
    endif
end

rm -f $TMPFILE

if ($pid != 0) then
    if ($debug || $verbse) \
	echo "killing sendmail daemon at pid $pid, restarting"
    if (! $debug) then
	kill -9 $pid
	/usr/lib/sendmail -bd -q1h
    endif
else
    echo "couldn't find sendmail to kill, restarting"
    if (! $debug) then
	/usr/lib/sendmail -bd -q1h
    endif
endif
