/* Filedescr2Comment.br by Troels Walsted Hansen
** $VER: Filedescr2Comment.br v1.00 (21.01.95)
**
** Search for the description of a file in THOR's filedatabase and add the
** description to the file as a filecomment. The script takes one argument
** on the commandline, and that is the path to a directory. All files in
** this directory, with a matching filecomment, will be searched for in the
** filedatabase of the BBS they were downloaded from, and their comment
** will be updated.
**
** Requirements:
**  · at least THOR 2.0 Pre1
**  · the existing filecomment should look like this:
**    "<bbsname>, <cpsvalue> cps" (NComm style)
**  · an existing and complete filedatabase
**  · the names of the BBSes must be the same in THOR and in NComm
**  · list, delete and filenote system commands in the searchpath
*/

parse arg dir
options results

/* needs bbsread.library functions */

if ~show('p', 'BBSREAD') then
do
	address command
		"run >nil: `GetEnv THOR/THORPath`bin/LoadBBSRead"
		"WaitForPort BBSREAD"
end

/* shouldn't assume that the dirname ends with ":" or "/" */

endchar = right(dir, 1)
if(endchar ~= ":" & endchar ~= "/") then dir = dir || '/'

/* make a list of the files and their comments */

address command 'list ' || '"' || dir || '"' || ' lformat="%-30N %C" >t:TempFilelistFile'

call open(lfh,"t:TempFilelistFile", R)

do forever
	str = readln(lfh)
	if(str = "") then break

	filename = strip(substr(str, 1, 30), B, " ")
	if(statef(dir||filename) = "DIR") then iterate

	comment = strip(substr(str, 32), B, " ")
	if(comment = "" | word(comment, words(comment)) ~= "cps") then iterate

	commapos = pos(",", comment)-1
	if(commapos < 1) then iterate

	bbs = substr(comment, 1, commapos)

	address(bbsread)
	SEARCHBRFILE bbsname '"'bbs'"' stem SRESULT search '"'filename'"' NAME
	if(rc ~= 0 | SRESULT.FILEAREA.COUNT < 1) then iterate

	READBRFILE bbsname '"'bbs'"' fareaname '"'SRESULT.FILEAREA.1'"' filenr '"'SRESULT.FILE.1.1'"' tagsstem FTAGS
	if(rc ~= 0) then iterate

	newcomment = ""

	do i=1 to FTAGS.DESCRIPTION.COUNT
		newcomment = newcomment || FTAGS.DESCRIPTION.i
	end

	/* write the new comment */

	say 'Filename............: ' || filename
	say 'Old description.....: ' || comment
	say 'New description.....: ' || newcomment
	say ''

	address command 'filenote ' || '"' || dir || filename || '"' || ' ' || '"' || newcomment || '"' || ' QUIET'
end

call close(lfh)

address command "delete >nil: t:TempFilelistFile"
