#!/bin/sh
#
# spoolqwk
#
# Usage: spoolqwk /some/directory/path/INFONEWS.zip
#
# Takes INFONEWS.zip files created with getnews on quics and
# spools them into your local CNews system.
#
# Created       Feb 07 1995  
#               Trever Miller (bug@cyberdex.cuug.ab.ca || tamiller@quics)
#
# Last Updated  Feb 09 1995
#               Trever Miller (bug@cyberdex.cuug.ab.ca || tamiller@quics)
#
#               Added usage message, more error checking, better Newsgroups:
#               parsing, and snag news setup info from /usr/lib/news/bin/config
#

if [ $# -le 0 ] || [ $# -ge 1 -a ! -r $1 ] ; then
  echo "\nUsage: `basename $0` /some/directory/path/INFONEWS.zip"
  exit 99
fi 

if [ -r /usr/lib/news/bin/config ] ; then
  . /usr/lib/news/bin/config
else
  echo "Unable to find news configuration.  Aborting."
  exit 99
fi

PATH=$PATH:$NEWSPATH ; export PATH

TEMPDIR=/usr/tmp/quics_tmp
mkdir $TEMPDIR 2>/dev/null

echo "Copying input files to temporary workspace"
cp $* $TEMPDIR
cd $TEMPDIR

for ZIPFILE in $*
do
  echo "\nProcessing "$ZIPFILE
  unzip $ZIPFILE '*MSG'
  rm -f $ZIPFILE

  # fix file permissions
  chmod 644 *MSG 

  # Make sure all newsgroups are existing first.
  #
  echo "\n  Checking for new Newsgroups:"

#
# Old method  -- Too easy for it to be fooled
#
#  ( for MSGFILE in *MSG
#    do
#      grep '^Newsgroups:' $MSGFILE | head -1 | cut -c13-200 |\
#        awk '{gsub(",","\n",$0);print}'
#    done
#  ) | sort -u >grouplist

#
# new method  -- can still be fooled, but not as easily.
#
  ( for MSGFILE in *MSG
    do
      awk '
        BEGIN {state="header"}

        $1 == "Newsgroups:" && state=="header" {
          $1=""
          gsub(",","\n",$0)
          print
          state="body"
        } 

        $0 ~ /^"#! rnews"/ && NF==3 { state="header" }

      ' < $MSGFILE
    done
  ) | sort -u >grouplist

  for GROUP in `cat grouplist`
  do
     gexists=`grep $GROUP /usr/lib/news/active`
     if [ $gexists ]
     then
     	:
     else
       echo "  Creating $GROUP\n"
       $NEWSBIN/maint/addgroup $GROUP y
     fi
  done
  rm -f grouplist
 
  echo 
  for MSGFILE in *MSG
  do
    echo "  Spooling "$MSGFILE
    $NEWSBIN/rnews <$MSGFILE
    rm -f $MSGFILE
  done
  
done
  
# now force them into the newsspool
echo "\nStarting newsrun (Acme disk grinder)"
$NEWSBIN/input/newsrun

echo "Spoolqwk has finished."

exit 0
## EOF spoolqwk
