--[[
---------------------------------------------------------------------------
Remote Train Control Program for Windows

© Copyright 2019 by Mark DiVecchio

	This file is part of Remote Train Control.

	Remote Train Control is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Remote Train Control is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Remote Train Control.  If not, see <http://www.gnu.org/licenses/>.

 Home Page : http://www.silogic.com/trains/RTC_Running.html
---------------------------------------------------------------------------]]
-- Semicolons are not required in Lua code
-- ftp Transfer Test
title = "HTTP Link Test"
-----------------------------------------------------------------------------
-- Little program that checks links in HTML files, using coroutines and
-- non-blocking I/O via the dispatcher module.
-- LuaSocket sample files
-- Author: Diego Nehab
--
-- Gets this error which usualy means the link is no good
--Error 2 running function setup() : E:\Projects\Remote_Control\Win32\Debug\lua\dispatch.lua:62: E:\Projects\Remote_Control\Win32\Debug\lua\ssl.lua:29: attempt to call a nil value (global 'unpack')
--
-----------------------------------------------------------------------------
local url = require("socket.url")
local dispatch = require("dispatch")
local http = require("socket.http")
dispatch.TIMEOUT = 10

local nthreads = 0

-- get the status of a URL using the dispatcher
function getstatus(link)
	local r, c, h, s
    local parsed = url.parse(link, {scheme = "file"})
	--print("Check Link: " .. link);
	--print("Scheme: " .. parsed.scheme)
    if parsed.scheme == "http" then
        nthreads = nthreads + 1
        handler:start(function()
            r, c, h, s = http.request{
                method = "HEAD",
                url = link,
                create = handler.tcp
            }
			nthreads = nthreads - 1
            if r and c == 200 then
				print('\t', link, ': OK')
				else
				print('\t', link, ': ', tostring(c))
				end
        end)
		-- exit on error
		--if (r and c ~= 200) then
		--	return false
		--	end
    end
	return true;
end

function readfile(path)
    path = url.unescape(path)
    local file, error = io.open(path, "r")
    if file then
        local body = file:read("*a")
        file:close()
        return body
    else return nil, error end
end

function load(u)
    local parsed = url.parse(u, { scheme = "file" })
    local body, headers, code, error
    local base = u
    if parsed.scheme == "http" then
        body, code, headers = http.request(u)
        if code == 200 then
            -- if there was a redirect, update base to reflect it
            base = headers.location or base
        end
        if not body then
            error = code
        end
    elseif parsed.scheme == "file" then
        body, error = readfile(parsed.path)
    else error = string.format("unhandled scheme '%s'", parsed.scheme) end
    return base, body, error
end

function getlinks(body, base)
	print("getlinks base " .. base);
    -- get rid of comments
    body = string.gsub(body, "%<%!%-%-.-%-%-%>", "")
	-- convert &amp; to &
    body = string.gsub(body, "%&amp;", "&")	
	-- convert %20 to a space
    body = string.gsub(body, "%%20", " ")
    local links = {}
    -- extract links
	-- not based on this but it might be a better regex
	-- https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url
    body = string.gsub(body, '[Hh][Rr][Ee][Ff]%s*=%s*"([^"]*)"', function(href)
    --body = string.gsub(body, '[Hh][Rr][Ee][Ff]%s*=%s*([^"]*)', function(href)
		--print("gsub1 ", base, "  ", href)
        table.insert(links, url.absolute(base, href))
    end)
    body = string.gsub(body, "[Hh][Rr][Ee][Ff]%s*=%s*'([^']*)'", function(href)
		--print("gsub2 ", base, "  ", href)
        table.insert(links, url.absolute(base, href))
    end)
-- the next gsub causes links to be detected twice and puts quotes about them
-- which causes getstatus() to fail
--    string.gsub(body, "[Hh][Rr][Ee][Ff]%s*=%s*(.-)>", function(href)
--		print("gsub3 ", base, "  ", href)
--        table.insert(links, url.absolute(base, href))
--    end)
    return links
end

function checklinks(address)
	local cnt = 0;
	print("Address: " .. address)
    local base, body, error = load(address)
    if not body then print(error) return end
    --print("Checking ", base)
    local links = getlinks(body, base)
    for _, link in ipairs(links) do
		print("link(".. cnt .. "): " .. link);
		cnt = cnt + 1;
		--getstatus(link)
        if (not getstatus(link)) then
			print ("getstatus() failed");
			return
			end
    end
end

-- main program
function setup() 
print("HTTPS test");

-- make sure the user knows how to invoke us
-- '-n' means we are running in non-blocking mode
if (false) then
    -- if non-blocking I/O was requested, use real dispatcher interface
    handler = dispatch.newhandler("coroutine")
	print("Non-blocking I/O");
else
    -- if using blocking I/O, use fake dispatcher interface
    handler = dispatch.newhandler("sequential")
	print("Blocking I/O")
end

--address = "http://www.silogic.com/index.html"
--address = "http://www.silogic.com/genealogy/index.htm"
--address = "http://www.silogic.com/genealogy/Mark_Camillo_DiVecchio.html"
--address = "http://www.silogic.com/genealogy/Betty_DiVecchio.html"
--address = "http://www.silogic.com/trains/RTC_Running.html"
address = "http://www.silogic.com/PEPE/PEPE.html"
--print("absolute " .. url.absolute("file:", address))
checklinks(url.absolute("file:", address))
while nthreads > 0 do
    handler:step()
end
print("Done");

return false;
end