/*
 */

sitefile="UULIB:sitename"                           /* Holds full sitename */
mqueue="TCPIP:Spool/Mqueue/"                        /* Must end in slash   */
nqueue="TCPIP:Spool/Nqueue/"                        /* Must end in slash   */
batchfile="UUSPOOL:batch/demon"                     /* List of postings    */
tempfile="T:NNTPPost-Temp"                          /* Tempory work file   */

/* Format of the files in the Nqueue directory are as follows...
 *
 * <seq>.txt   contains the header and body of the message
 * <seq>.wrk   contains the information for NNTP
 *
 * A typical entry for <seq>.wrk would look like this...
 *
 * <1> <dan.0001@blender.demon.co.uk>   <article's message id>
 */

if open(batchfile,batchfile,"r")==0 then
  exit 0

sitename=""
if exists("UUCP:sitename") then
  sitefile="UUCP:sitename"
if open(sitefile,sitefile,"r")==1 then do
  sitename=readln(sitefile)
  close(sitefile)
end
if sitename=="" then do
  say "Couldn't open UULIB:sitename or UUCP:sitename for reading"
  exit 20
end

seqfile=mqueue||"sequence.seq"
if open(seqfile,seqfile,"r")==0 then
  sequence=1
else do
  sequence=""
  sequence=readln(seqfile)
  if sequence=="" then
    sequence=1
  close(seqfile)
end

do forever
  article=readln(batchfile)
  if eof(batchfile) then
    leave

  sequence=sequence+1
  say "Processing sequence" sequence||"..."

  article="UUNEWS:"||translate(article,"/",".")
  if open(article,article,"r")==0 then do
    say "Couldn't open" article "for reading"
    sequence=sequence-1
    iterate
  end

  lckfile=nqueue||sequence||".lck"
  address command "echo >"||lckfile

  txtfile=nqueue||sequence||".txt"
  if open(txtfile,txtfile,"w")==0 then do
    say "Couldn't open" article||"'s file" txtfile "for writing"
    sequence=sequence-1
    close(article)
    address command "delete >nil:" lckfile
    iterate
  end

  headlines=0
  do forever
    string=readln(article)
    headlines=headlines+1
    if string=="" then
      leave
    else if upper(left(string,12))=="MESSAGE-ID: " then
      messageid=string
    else if left(string,6)=="Path: " then
      string="Path:" sitename||"!"||substr(string,7)
    writeln(txtfile,string)
  end
  close(txtfile)
  close(article)
  address command "tail +"||headlines-1 article ">>"||txtfile

  wrkfile=nqueue||sequence||".wrk"
  if open(wrkfile,wrkfile,"w")==0 then do
    say "Couldn't open" article||"'s file" wrkfile "for writing"
    sequence=sequence-1
    address command "delete >nil:" txtfile
    address command "delete >nil:" lckfile
    iterate
  end
  writeln(wrkfile,substr(messageid,13))
  close(wrkfile)

  address command "delete >nil:" lckfile
end
close(batchfile)

address command "delete >nil:" tempfile
address command "delete >nil:" batchfile||".done"
address command "rename >nil:" batchfile batchfile||".done"

if open(seqfile,seqfile,"w")==0 then do
  say "Couldn't open" seqfile "for a rewrite - it should be" sequence
  exit 20
end
writeln(seqfile,sequence)
close(seqfile)
