/*
 * $VER: NewGroup.rexx 1.01 (20.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.
 * It takes only one argument: the number of days to keep news for new groups,
 * defaulting to 7.
 *
 * New since 1.0:
 *
 *	- now deletes the temporary file...
 *  - expiry days are now picked up from the command line
 *  - simplified 
 *
 */

options failat 21
address command
days = strip(arg(1))
if days = '' | days = 0 | ~datatype(days, 'num') then days = 7

/* some defines */
ret = 0
number = 0
action = 0 

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(word(readln(groups), 1))
		if 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 = 0 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 = strip(word(line, 3))
									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
'delete >nil: t:newgroups.tmp'
exit ret
