#!/bin/csh

# Script to retrieve WAIS documents for ServiceMail
# Jim Davis Aug 25 1992

if ($#argv == 0) goto usage

set source = $HOME/.wais-sources
set boundary = DOCUMENT
set question = $1
shift

while ($#argv > 0)
  switch ($1)
  case -s:
   shift
   if ($#argv < 1) goto usage
   set source = $1
   shift
   breaksw
 case -b:
   shift
   if ($#argv < 1) goto usage
   set boundary = $1
   shift
   breaksw
 default:
   goto usage
   breaksw
 endsw
end

# remove any garbage from head of the message, e.g. mail headers

set tempq = /tmp/question$$
	
if (-e $question) else
 echo Question file $question does not exist.
 exit 1
endif

if (-d $source) else
 echo WAIS sources directory $source does not exist.
 exit 1
endif

awk '/\(:question/ {ok=1}\
     /^Searching:/ {ok=0}\
                   {if (ok == 1) print}' $question > $tempq

# Now find out how many documents there are
set temp = /tmp/waisq$$
set result = /tmp/doc$$
waisq -f $tempq -s $source -g >& $temp
echo "" >> $temp
set count = `tail -1 $temp | sed -e 's/^.*Found //' | sed -e 's/ item.*$//'`

echo -n Retrieving $count document
if ($count == 1) then
 echo ""
else
 echo "s"
endif

# Now get each one.

set i = 1

rm $temp
touch $temp

while ($i <= $count)
 # insert MIME boundary
 echo --${boundary} >> $temp
 waisq -s $source -f $tempq -v $i > $result
 if ("`head -1 $result | awk '/Mime Version/{print 1}'`" != 1) then
   # if it is not a MIME document, insert blank line
   echo "" >> $temp
 endif
 cat $result >> $temp
 @ i ++
end
# final MIME boundary
echo --${boundary}-- >> $temp

cat $temp

rm $tempq $temp $result
exit 0

usage:
 echo "usage: `basename $0` QUESTION [-s SOURCE-DIR] [-b BOUNDARY-STRING]"
 exit 1
