/* --------------------------------------------------------------------
	Call the HTTP submit program to send a request to the local server.
	This is not a stand-alone program, it is to be used as a subroutine.

	Arguments:
		http		=	the command string to send
		user		=	name of a user with admin privileges
		password	=	password for that user
		begin_at	=	the string to look for before echoing the response
		end_at	=	the string to look for to stop echoing the response
	--------------------------------------------------------------------	*/

http 		= arg(1)
user		= arg(2) 
password	= arg(3)
begin_at	= arg(4)
end_at	= arg(5)

call RxFuncAdd 'SysTempFileName', 'RexxUtil', 'SysTempFileName'
call RxFuncAdd 'SysFileDelete', 'RexxUtil', 'SysFileDelete'

/* Submit the request, capturing output to a temporary file. */

filename = SysTempFileName("h?????.rsp")

if length(user) > 0 then
	'@submit "'http'" -u'user':'password' >'filename '2>&1'
else
	'@submit "'http'" >'filename

/* Read the response and extract only the relevant portion. */

begun = 0
ended = 0
doall = 0

call stream filename, 'C', 'open read'

/* The first line should always be an HTTP response */

response = linein(filename)
if pos("HTTP/", response) != 1 then do
	doall = 1
	say response
end
else do
	parse value response with protocol status message

	if \(status = 200) then do
		say message
		return
	end
end

do while \ended & lines(filename)
	response = linein(filename)

	if doall then
		say response
	else if begun then do
		if pos(end_at, response) > 0 then
			ended = 1
		else do 

			/* remove the HTML markup tags */
			answer = ''
			do while length(response) > 0
				parse value response with keep '<' discard '>' response
				answer = answer keep
			end

			/* echo the response from the server to the console */
			say strip(answer)
		end
	end
	else if pos(begin_at, response) > 0 then do
		begun = 1
	end
end

/* Remove the file containing the response. */

call stream filename, 'C', 'close'
call SysFileDelete filename

return

