/*
 * $VER: ncFTPevents.br 1.32 (23.06.96) Shaun Downend.
 *          <shaund@amiganut.demon.co.uk>
 *
 * Does not require Thor to be running. Requires Thor 2.3+ installed with
 * a TCP system set up and download events enabled (not default - see
 * Thor/s/cftcp).
 *
 * Uses ncFTP to fetch the files - this is part of the standard AmiTCP
 * installation.
 *
 * The script permits an optional command line argument which consists of
 * an alternative Aminet mirror site.
 *
 * Change the settings below to suit your setup:-
 */

bbs = 'Internet'                	/* name of your TCP system 			*/
conf = 'EMail'				/* name of email conference 			*/
aminet = 'ftp.aminet.org'	  	/* insert your local Aminet mirror here 	*/
mainaminet = 'wuarchive.wustl.edu'	/* main aminet site 				*/
downloaddir = 'downloads:new/untested/'	/* path to where the files will be downloaded 	*/
ncFTPpath = 'AmiTCP:bin/'		/* path to ncFTP 				*/
logfile = 1				/* output log to email message? 		*/
retry = 0                               /* mark the event as ERR or leave it active 	*/
trymain = 1				/* If any (new)files are not found then auto try*
                                         * the main aminet site.			*/

/* Do not change anything below here! */

options results
options failat 21

/* Did the user specify an alternative Aminet mirror? */

parse arg mirror
if mirror ~= '' then aminet = mirror

/* check configured paths are valid ( anything to keep Paul Copsey happy ;-) */

call checkpath(downloaddir)
downloaddir = checked_path

call checkpath(ncFTPpath)
ncFTPpath = checked_path

if trymain = 1 then
do
	userretry = retry
	retry = 1
end
else userretry = retry

tempdir = 'T:'
ncftplog = ''tempdir'ncftp.log'		/* ncftp logfile (used for verification *
					 *           and CPS rates)             */

EVE_DOWNLOAD	=  4     	/* Upload file      */
EDF_ACTIVE  	= '00000000'x   /* Event is active  */
EDF_DELETED 	= '00000001'x   /* Event is deleted */
EDF_DONE    	= '00000004'x   /* Event is done    */
EDF_ERROR   	= '00000008'x   /* Error with Event */
EDF_FREEZE	= '00000020'x	/* Event is frozen  */

/* needs bbsread.library functions */

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

/* get first and last event numbers */

address(bbsread)

GETBBSDATA '"'bbs'"' stem BBSDATA
if(rc ~= 0) then
do
        say BBSREAD.LASTERROR
        exit 5
end

/* prepare info to create email log file */

drop MSG.

MSG.FROMNAME = 'ncFTPevents.br'
MSG.TONAME   = BBSDATA.USERNAME
MSG.ORGINALNR = 1
MSG.SUBJECT = 'FTP logfile'


/* Initialise body text line counter for logfile */

c = 0

call addmsgtxt('')
call addmsgtxt('System: 'BBSDATA.NAME'   Method: ncFTP   Download Dir: 'downloaddir'')
call addmsgtxt('')
call addmsgtxt(''time()' Processing events...')
call addmsgtxt('')


MSG.PART.COUNT = 0

call createFTPscript

events = 0

call processevents

call closeFTPscript

call addmsgtxt('')
call addmsgtxt(''time()' Completed events.')
call addmsgtxt('')

call ftpevents

if errors = 1 & trymain = 1 then
do
	errors = 0
	retry = userretry
	call addmsgtxt('')
	call addmsgtxt('There were errors. Trying main Aminet site...')
	call addmsgtxt('')
	aminet = mainaminet
	call createFTPscript
	call addmsgtxt(''time()' Processing outstanding events...')
	call addmsgtxt('')
	call processevents
	call closeFTPscript
	call addmsgtxt('')
	call addmsgtxt(''time()' Completed events.')
	call addmsgtxt('')
	call ftpevents
end

if errors = 0 then
do
	/* tell bbsread.library to remove the marked events permanently */

	PACKDATAFILE BBSNAME '"'bbs'"' EVENTDATA
	if(rc ~= 0) then
	do
	        say BBSREAD.LASTERROR
	        exit 5
	end
	call addmsgtxt('')
	call addmsgtxt('Operation successful! All files downloaded.')
end
else
do
	call addmsgtxt('')
	call addmsgtxt('Operation not entirely successful! There were errors.')
end

call writemsg
exit

/* end of main script - functions follow */

writemsg:

MSG.TEXT.COUNT = c

/* Write a log file if there are events and the user has requested a log
 * file.
 */

if events == 1 & logfile == 1 then
do
	/* Write logfile */

	urg = ''
	if errors = 1 then urg = 'URGENT'

	WRITEBRMESSAGE BBSDATA.NAME conf stem MSG urg
	if(rc ~= 0) then
	do
		say BBSREAD.LASTERROR
	        exit
	end

	/* Check to see if Thor is running. If so inform the user of success or
 	 * failure.
 	 */

	p=' '||address()||' '||show('P',,)
	if pos(' THOR.',p)>0 then                       /* Thanks Troels! */
   	thorport=word(substr(p,pos(' THOR.',p)+1),1)
	else exit
	address(thorport)
	thortofront
	isconferencelist
	if rc = 0 then updateconfwindow
	drop CUR.
	currentmsg stem CUR
	if(rc ~= 0) then say THOR.LASTERROR
	else
	do
		upper conf CUR.CONFNAME
		if CUR.CONFNAME = conf then showconference conf
	end
        if errors == 0 then
	do
		requestnotify text '"ncFTPevents.br   \nOperation successful!"' BT "_OK"
        	if(rc ~= 0) then
     		do
			say THOR.LASTERROR
			exit
		end
	end
	else
	do
	requestnotify text '"ncFTPevents.br\n'thorerror'"' BT "_OK"
        	if(rc ~= 0) then
     		do
			say THOR.LASTERROR
			exit
		end
	end
end
return

addmsgtxt:	/* add information to the logfile */
parse arg txt
c = c + 1
MSG.TEXT.c = txt
return

ftpfail:	/* Event unsuccessfully ftp'd */
errors = 1
thorerror = 'Operation not entirely successful!'
if retry == 0 then
do
	UPDATEBREVENT BBSNAME '"'bbs'"' EVENTNR i SETERROR
	if(rc ~= 0) then
	do
		say BBSREAD.LASTERROR
		call addmsgtxt(''time()' 'i' ERROR: Download: Could not mark event as error!')
		end
end
return

checkpath:	/* check configured paths are valid */
parse arg file_path
if ((right(file_path,1) ~='/') & (right(file_path,1) ~=':')) then
do
	if index(file_path,':') > 0 then checked_path=file_path || '/'
	else checked_path=file_path || ':'
end
else
checked_path = file_path
if ~exists(checked_path) then
do
        say ''checked_path' doesn''t exist! Bad Path! Please check your configuration.'
	exit(10)
end
return

processevents:	/* process all active download events */
do i=BBSDATA.FIRSTEVENT to BBSDATA.LASTEVENT

        drop EVENTDATA.

        READBREVENT bbsname bbs eventnr i datastem EVENTDATA
        if(rc ~= 0) then
        do
                say BBSREAD.LASTERROR
                exit
        end

	/* check to see if it is a download event */

        if EVENTDATA.EVENTTYPE = EVE_DOWNLOAD then
        do

		/* and make sure the event is active */

                if EVENTDATA.FLAGS=EDF_ACTIVE then
                do
                        drop EVENTTAGS.

                        READBREVENT bbsname bbs eventnr i tagsstem EVENTTAGS
                        if(rc ~= 0) then
                        do
                                 say BBSREAD.LASTERROR
                                 exit
                        end

			call addmsgtxt(''time()' 'i' DOWNLOAD: 'EVENTTAGS.DIRECTORY'/'EVENTTAGS.FILENAME'')

                        /* add entry to batch file */

                        call writeln(ftpbat,'get 'EVENTTAGS.DIRECTORY'/'EVENTTAGS.FILENAME'')
                        events = 1
                end
		else
		if (EVENTDATA.FLAGS = EDF_FREEZE) then call addmsgtxt(''time()' 'i' INFO: Event is not active, skipping...')
        end
end
return

createFTPscript:	/* initialise ftp script file for ncFTP */
if(~OPEN(ftpbat,''tempdir'ncftp.script','Write')) then
        do
                say 'Unable to open file'
                exit
        end

call writeln(ftpbat,'set logfile 'ncftplog'')
call writeln(ftpbat,'set local-dir 'downloaddir'')
call writeln(ftpbat,'set progress-reports 2')
call writeln(ftpbat,'set verbose 1')
call writeln(ftpbat,'open 'aminet':pub/aminet/')
return

closeFTPscript:
call writeln(ftpbat,'quit')
call close(ftpbat)
return

ftpevents:	/* ftp all active download events */
if events = 1 then 	/* are there any active download events? */
do
	call addmsgtxt('Aminet mirror: 'aminet'')
	call addmsgtxt('')
	call addmsgtxt(''time()' ncFTP Started.')
	address command ''ncFTPpath'ncftp <'tempdir'ncftp.script >CON:0/100/550/300/ncFTP/CLOSE/AUTO'
	ncftpstatus = rc

	call addmsgtxt(''time()' ncFTP Completed.')
	call addmsgtxt('')

	address command 'c:delete >NIL: 'tempdir'ncftp.script'
	if(rc ~=0) then say 'Could not delete 'tempdir'ncftp.script!'

        if ncftpstatus = 20 then
	do
		call addmsgtxt('ncFTP failed.')
		call addmsgtxt('Do you have AmiTCP running?')
	        thorerror = 'ncFTP failed. AmiTCP is not running.'
		call writemsg
		exit
	end

        if ncftpstatus = 10 then
	do
		call addmsgtxt('ncFTP failed.')
		call addmsgtxt('Have you selected the correct path for ncFTP?')
	        thorerror = 'ncFTP failed. Check the path for ncFTP.'
		call writemsg
		exit
	end

	if(~OPEN(slog,''tempdir'ncftp.log','read')) then
        do
		call addmsgtxt('Unable to open a connection to 'aminet'.')
		thorerror = 'Unable to open a connection to 'aminet'.'
		call writemsg
                exit
        end

        /* Read ncFTP logfile and determine if a connection was made */

	line = READLN(slog)

        if pos('opened',line) = 0 then
	do
		call close(slog)
		call addmsgtxt('Could not open a connection to 'aminet'.')
                thorerror = 'Unable to open a connection to 'aminet'.'
		address command 'c:delete >NIL: 'tempdir'ncftp.log'
		call writemsg
		exit
	end


	/* Now verify that the files have been ftp'd successfully */

	call addmsgtxt(''time()' Verifying files...')
	call addmsgtxt('')

	errors = 0

	do i=BBSDATA.FIRSTEVENT to BBSDATA.LASTEVENT

        	drop EVENTDATA.

	        READBREVENT bbsname bbs eventnr i datastem EVENTDATA
	        if(rc ~= 0) then
	        do
	                say BBSREAD.LASTERROR
	                exit
	        end

		/* check to see if it is a download event */

	        if EVENTDATA.EVENTTYPE = EVE_DOWNLOAD then
	        do

			/* and make sure the event is active */

	                if EVENTDATA.FLAGS=EDF_ACTIVE then
	                do
	                        drop EVENTTAGS.

	                        READBREVENT bbsname bbs eventnr i tagsstem EVENTTAGS
	                        if(rc ~= 0) then
	                        do
	                                 say BBSREAD.LASTERROR
	                                 exit
	                        end

				line = READLN(slog)

                                if (exists(''downloaddir''EVENTTAGS.FILENAME'')) = 1 then
				do
        				if pos(EVENTTAGS.FILENAME,line) > 1 then
					do
						parse var line 'received,' cps
						cps = strip(cps)
						if ((left(cps,1) ~='-')) then
						do
                                                        if ((left(cps,4) ~='0.00')) then
							do
								if cps ~= '' then
								do
									/* Event successfully ftp'd */

									call addmsgtxt(''time()' 'i' OK: 'EVENTTAGS.FILENAME' downloaded. 'cps'')
		                        				UPDATEBREVENT BBSNAME '"'bbs'"' EVENTNR i SETDONE
		                        				if(rc ~= 0) then
			                        			do
			                        				say BBSREAD.LASTERROR
										call addmsgtxt(''time()' 'i' ERROR: Could not mark the event as done!')
			                	        		end
								end
								else
								do
									call addmsgtxt(''time()' 'i' ERROR: 'EVENTTAGS.FILENAME' failed. File not found.')
									call ftpfail
								end
							end
							else
							do
                                                        	call addmsgtxt(''time()' 'i' ERROR: 'EVENTTAGS.FILENAME' failed. File not found.')
								call ftpfail
							end
						end
						else
						do
							call addmsgtxt(''time()' 'i' ERROR: 'EVENTTAGS.FILENAME' failed. Transfer interrupted.')
							call ftpfail
							call close(slog)
							address command 'c:delete >NIL: 'tempdir'ncftp.log'
							if(rc ~=0) then say 'Could not delete 'tempdir'ncftp.log!'
                                                        call writemsg
                                                        exit(10)
						end
					end
					else
					do
						call addmsgtxt(''time()' 'i' ERROR: 'EVENTTAGS.FILENAME' failed.')
						call ftpfail
					end
				end
				else
				do
					call addmsgtxt(''time()' 'i' ERROR: 'EVENTTAGS.FILENAME' failed. File not found.')
					call ftpfail
				end
	                end
	        end
	end

	call close(slog)
	address command 'c:delete >NIL: 'tempdir'ncftp.log'
	if(rc ~=0) then say 'Could not delete 'tempdir'ncftp.log!'

end

else
do
	call addmsgtxt(''time()' No active events. Exiting...')
	address command 'c:delete >NIL: 'tempdir'ncftp.script'
	if(rc ~=0) then say 'Could not delete 'tempdir'ncftp.script!'
end
return
