/*
 * $VER: NewGroup.rexx 1.0 (11.11.94)
 *
 * Created by Lauri Aalto <kilroy@fipnet.fi>, Public Domain.
 *
 * Scans UUNEWS:control/#[0-9] for newgroup control messages and adds
 * them to UULIB:NewsGroups deleting processed control files.
 *
 * Just execute this from you UUXQT script, crontab, shell prompt or whatever.
 *
 */

options failat 21
address command

/* some defines */
ret = 0
number = 0
action = 0 
days = 2			/* set this # of days to keep news by default */

/* some more defines... */
control = 'Control: newgroup '
controllen = length(control)

/* read in newsgroups file for dupe checking */
newsgroups. = ''
count = 0
if open(groups, 'UULIB:NewsGroups', r) then do
	do while ~eof(groups)
		line = upper(compress(word(readln(groups), 1)))
		if compress(line) ~= "" then do
			 newsgroups.count = line
			count = count + 1
		end
	end
	call close groups
end
if open(groups, 'UULIB:NewsGroups', a) then do
	'list >t:newgroups.tmp UUNEWS:control/#[0-9] lformat %p%n'
	if ~rc then
		if open(tmp, 't:newgroups.tmp', r) then do
			do while ~eof(tmp)
				delete = 0
				name = readln(tmp)				
				if name ~= '' then 
					if open(file, name, r) then do
						mode = 1 /* header/body? */
						do while ~eof(file)
							line = readln(file)
							select
								when line = "" then mode = 0
								when mode & left(line, controllen) = control then do
									groupname = compress(right(line, length(line) - controllen))
									delete = 1
									valid = 1
									do i = 0 to count
										if upper(groupname) = newsgroups.i then valid = 0
									end
									if valid then do 
										call writeln groups, groupname days
										count = count + 1
										newsgroups.count = upper(groupname)
										say 'group' groupname 'added'
										number = number + 1
									end
									else say 'group' groupname 'already exists'
									action = 1
								end
								otherwise nop
							end
						end
						call close file
						if delete then 'delete quiet' name /* delete to avoid reprocessing this file */
				end											
				else do
					say 'Can''t open' name
					ret = 5
				end
			end
			call close tmp
	end
	else ret = rc
	call close groups
end
else do
	say 'Can''t open UULIB:NewsGroups'
	ret = 20
end
if action then say
if number = 1 then s = ''
else s = 's'
say 'NewGroup.rexx: added' number 'group' || s
exit ret
