#!/usr/bin/env luajit

--[[ Read the README file for what this is all about.
     If there is no README or similar, then you can find the link to the source below.

    Normally I define functions and globals at the top, but here I'm interleaving them.
]]

local Lunamark = require'lunamark'	-- https://github.com/jgm/lunamark
local Lpeg = require'lpeg'		-- https://www.inf.puc-rio.br/~roberto/lpeg/lpeg.html  Lunamark uses this, so we can to.
local RE = require're'		-- Part of lpeg.  https://www.inf.puc-rio.br/~roberto/lpeg/re.html
local _ = require'polygLua'

---------------------------------------------------------------------------------
-- Some global data.

local GlobalMetaData = {
    dlr = '&dollar;', perc = '%', dot = '.',
    devuanCinnabarDark   = '#310202',    devuanCinnabarLight  = '#510505',
    devuanDarkPurpyDark  = '#33313b',    devuanDarkPurpyLight = '#3c3a45',
    devuanDeepSeaDark    = '#132f40',    devuanDeepSeaLight   = '#1a4562',
    devuanSaphireDark    = '#004489',    devuanSaphireLight   = '#00509f',
    devuanDevuanDark     = '#000000',    devuanDevuanLight    = '#ffffff',
    -- HTML link colours.  Naturally HTML5 deprecated the simple version, replacing it with less simple CSS.
    -- <body> has alink, link, vlink; CSS has active, link, visited, and hover.
    devuanDevuanalink    = '#03a4ff',    devuanDevuanlink     = '#0076b6',    devuanDevuanvlink    = '#6aa4db',   devuanDevuanhlink   = '#03a4ff',
    devuanSDevuanalink   = '#98c3db',    devuanSDevuanlink    = '#ffffff',    devuanSDevuanvlink   = '#ffffff',   devuanSDevuanhlink  = '#98c3db',
    karenPurple          = '#8800ff',    onefangPurple        = '#cc00ff',    onefangGreen         = '#42ff00',
    PinkFloyd            = '#AA00AA',    DeepPurple           = '#220022',	-- From an ancient site of mine, which went from PinkFloyd to DeepPurple as a background gradient.
    favicon = 'nYAW_icon.png', logo = 'nYAW.png',
}

local Files, Subs, xLinks = {}, {}, {}
local Context = {}			-- Coz can't otherwise pass context through to the deeper Lunamark functions I'm overriding.

local Template = ''
local h = io.open('default.template', 'r')
if nil ~= h then
    Template = h:read('*a')	-- NOTE - Lua 5.3 changes to not need the *, but ignores it if it's there.
    h:close()
else
    E('oops! No such file ' .. 'default.template')
end


---------------------------------------------------------------------------------
-- Useful functions, part 0.

-- A simple table.subtable = subtable wont work, you end up with a reference so that changes to the later get applied to the former.
local derefiTable = function(t, strip)
    local argh = {}
    for l, y in ipairs(t) do	if (l ~= y.name) and strip then table.insert(argh, y) end	end
    return argh
end
local derefTable = function(t, strip)
    local argh = {}
    for l, y in pairs(t) do	argh[l] = y end
    return argh
end


local writeString = function(base, body)
    local a, e = io.open(base, 'w')
    if nil == a then print('Could not open ' .. base .. ' - ' .. e) else
	a:write(body)
	a:close()
    end
end


-- String together the bits array into a path string.  Or the other way around.  lol
local stringBits = function(l)
    local bits = {}
    local last = 1
    for j = 1, #l do
	if '/' == l:sub(j, j) then
	    table.insert(bits, l:sub(last, j - 1))
	    last = j + 1
	end
    end
    return bits, l:sub(last)
end


-- Put a value into the Files or Subs table, creating things if needed.
local toFile = function(name, key, value)
    if nil == Files[name] then
	local bits, bit = stringBits(name)
	local path = ''
	Files[name] = {}
	Files[name].headers = {}
	Files[name].bits = bits
	Files[name].bit = bit
	for i, d in ipairs(bits) do
	    if '' ~= path then path = path .. '/' end
	    path = path .. d
	end
	Files[name].path = path
--	Files[name].body = ''
	if ('Foswiki' == bits[1]) or ('PmWiki' == bits[1]) then Files[name].ogWiki = bits[1] end
    end
    if nil ~= key         then Files[name][key] = value end
    for i, v in ipairs{'metadata', 'bits', } do
	if nil == Files[name][v] then Files[name][v] = {} end
    end
    -- Open the files and do the initial cleanups.
    local body = ''
    if '.md' ~= name:sub(-3, -1) then
	h = io.open(name .. '.md', 'r')
	if nil ~= h then
--	    D('Parsing ' .. name .. '.md')
	    Context = Files[name]
	    body = h:read('*a') ; h:close()
	    -- Deal with my typical double spaced sentence endings, and other things.
	    local result = RE.compile( [=[{~
 (
  {[.?!]{"  "}}              -> '%1&nbsp;' /		-- '&nbsp;' gets turned into hex 0xA0 by parse().  So feed it another metadata token that gets translated to &nbsp;.  Seems we now skip this issue.
  {[\\]{['"|$]}}             -> '%2' /			-- Do the same for fixing the \' \" \| etc mess pandoc left.
  {"[ ]{.foswikiGrayFG}" }  -> '' /			-- Coz Foswiki sucks.  No idea why the next thing didn't catch it.
  {"[" {([^]])+} "]{.foswiki" {([^FG}])+} "FG}" }  -> "<span style='color: %3;'>%2</span>" /
  {"::: {."[A-Za-z_. ]+"}"}  -> '' /
  {":::"}                    -> '' /
  {"-noComment-"}            -> ' -- ' /
  {"| bgcolor=#" {([^ ])+} " " }  -> "| <span style='background: #%2;'> bgcolor=#%2 </span> " /		-- Deal with debdog's color table.
  {"[" {([^]])+} ']{style="color: ' {([^}])+} "}" }  -> "<span style='color: %3;'>%2</span>" /
  {"[" {([^]])+} "]{style='color: " {([^}])+} "}" }  -> "<span style='color: %3;'>%2</span>" /
  {"{#"[A-Za-z_]+"}"}        -> '' /
  {"### [[edit](/bin/edit/Main/" {([^%nl])+} }  -> '' /
  {"#"+ " " {([^%nl])+} }  -> header /
  .
 )* ~}]=],   { header = function(a) table.insert(Context.headers, a); return a end } ):match(body)
	    body = result
--  {"<!--".*"-->"}          -> '' /
--  {"[$]"}                  -> '$dlr$' /		-- Replace $, coz otherwise it confuses things later.
	    body = RE.gsub(body, '{[$]}', '$dlr$')
--  {"[%]"}                  -> '$perc$' /		-- Gotta be done after the %1's above. otherwise screws things up when included above.
--	    body = RE.gsub(body, '{[%]}', '$perc$')	-- Coz otherwise stray % trip up the capture part.
	end
	Files[name].body = body
    end
end
local toSub = function(name, key, value)
    if nil == Subs[name] then
	local bits, bit = stringBits(name)
	local path = ''
	Subs[name] = {}
	table.insert(bits, bit)
	Subs[name].bits = bits
	Subs[name].bit = bit
	for i, d in ipairs(bits) do
	    if '' ~= path then path = path .. '/' end
	    path = path .. d
	end
	Subs[name].path = path
    end
    if nil ~= key        then Subs[name][key] = value end
    for i, v in ipairs{'metadata', 'bits', 'files', 'subs'} do
	if nil == Subs[name][v] then Subs[name][v] = {} end
    end
end



local readMdMd = function(name, metadata)
	local h1 = io.open(name .. '.md')
	if nil == h1 then
--	    E('Could not open ' .. name .. '.md')
	    return {}
	else
	    for l in h1:lines() do
		for k, v in l:gmatch'(%w+)%s*=%s*(.+)' do 
		    if nil == v then
			P(name .. ' ' .. k)
		    else
			metadata[k] = v
		    end
		end
	    end
	end
	return metadata
end



local commonLinky = function(l, body, u, url, beg, en, beg0, en0, bump)
		if nil == url then
--		    W('OOPS! unknown linky  - @' .. l .. '\t\t\t' .. body:sub(beg - 9, en) .. ' ' .. body:sub(en + 1, en0))
		else
		    local md = readMdMd(url, {})
--		    if nil ~= md then
			if nil ~= md.realURL then url = md.realURL end
--		    end
		    body = body:sub(1, beg - bump) .. url .. body:sub(en0 + 1)
		    here = here + url:len()
	        end
	        if 1 == bump then
		    here = here + 1
		    beg, en = RE.find(body, [['https://fos.wiki.devuan.org/']], here)
		else
		    beg, en = RE.find(body, [["'https://wiki.devuan.org/"]], here)
		end
		return beg, en, body, here
end



--[[
]]


---------------------------------------------------------------------------------
-- Actually start doing things.

-- Create the base of everything.md here, so it gets picked up as usual in the file scan.
h = io.open('everything.md', 'w')
if nil ~= h then
    h:close()
else
    E"Can't open everything.md for writing."
end

-- Scan the sub folders looking for our files.
local Folder = arg[1]
toSub''
if nil == Folder then Folder = '.' end
--GlobalMetaData.root = Folder

--[[ Sort out realURL for symlinked .md.md files.
    realURL is the generic URL part for this page.  By policy it points to whatever is the latest copy / symlink of the original download .md.md.
    realURL starts out being the path to the downloaded file and friends.
    If we make a symlink during SuckIt, then that gets updated to point to the place the symlink is in.
	below we compare timestamps and select the latest version if there's more than one symlink.
    For the "page symlinked" problem, this should work if realURL is kept updated.
    For the "page copied"    problem, this should work if realURL is kept updated, same as symlinked really, coz that's just another copy.
    For the "page moved"     problem, that'll be the most recent symlink, the old one still has it's symlink pointing to the download .md.md, which gets updated with the current realURL.
	So when some external old URL points to someplace a page used to be, it's old symlink points to the up to date download .md.md, and we know where to go to find the page now.
	A left over .md.md file should have a redirect .HTML page created for it.
]]
for l in io.popen('find -L ' .. Folder .. ' -name unsorted -prune -o -name "*.md.md" -xtype l -printf "%P\n"'):lines() do
    local metadata = readMdMd(l:sub(1, -4), {})
    if nil == metadata.realURL then
	metadata.realURL = l:sub(1, -7)
    else
	if metadata.realURL ~= l:sub(1, -7) then
	    metadata.realURL = l:sub(1, -7)
	    -- If this already exists, compare the timestamps, most recent wins.
	    local time0 = io.popen('ls -l --time-style=+%s "' .. metadata.realURL .. '.md.md" | cut -d \' \' -f 6'):read('l')
	    local time1 = io.popen('ls -l --time-style=+%s "' ..                l ..       '" | cut -d \' \' -f 6'):read('l')
	    if time0 > time1 then		metadata = nil end
	else					metadata = nil end
    end

    if nil ~= metadata then
-- DUNNO if this writes to the original file, or overwrites the symlink.
	local a, e = io.open(l, 'w')
	if nil == a then E('Could not open ' .. l .. ' - ' .. e) else
	    for k, v in pairs(metadata) do
		a:write(k .. '=' .. v .. '\n')
	    end
	    a:close()
	end
    end
end

-- Clean up unsorted.
for l in io.popen('find -L ' .. Folder .. ' -name unsorted -prune -o -name "*.md" -a -not -name "*.md.md" -xtype l -printf "%P\n"'):lines() do
    local tp = '_fos'
    local metadata = readMdMd(l, {})
    if nil ~= metadata then
	if 'PmWiki' == metadata.ogWiki then tp = '_pm' end
	if nil ~= metadata.ogFile then
	    local unsort = 'unsorted/' .. metadata.ogFile
	    local a, e = io.open(unsort .. tp .. '.md' , 'r')
	    if nil ~= a then
		a:close()
		-- Keep the .md.md symlink, delete the rest.
		os.execute('rm ' .. unsort .. tp .. '.HTML')
		os.execute('rm ' .. unsort .. tp .. '.md')
		a, e = io.open(unsort .. tp .. '.HTML', 'w')
		if nil == a then E('Could not open ' .. unsort .. tp .. '.HTML' .. ' - ' .. e) else
		    local dst = l:sub(1, -4) .. '.HTML'
		    local cnt = 1
		    for j = 1, #metadata.ogFile do
			if '/' == metadata.ogFile:sub(j, j) then cnt = cnt + 1 end
		    end
		    dst = string.rep('../', cnt) .. dst
		    a:write(
[=[<!DOCTYPE html>
<html>
  <head><meta http-equiv="refresh" content="0; url=]=] .. dst .. '"' .. [=[/></head>
  <body><p>Click this if you don't get redirected to the real page - <a href="]=] .. dst .. '"' .. [=[>Redirect</a></p></body>
</html>
]=])
		    a:close()
		    W('REDIRECT ' .. unsort .. tp .. '.HTML \t-> ' .. dst)
		end

	    end
	end
    end
end

-- Look for copied pages from the other wikis.
for l in io.popen('find -L ' .. Folder .. ' -name "*.HTM" -type f,l -printf "%P\n"'):lines() do
-- Only do this if .HTM is newer than .md, or .md doesn't exist.
    local htime = io.popen('date -ur ' ..            l ..           ' +%s'):read('l')
    local mtime = io.popen('date -ur ' .. l:sub(1, -4) .. 'md +%s 2>/dev/null'):read('l')
    if (nil == mtime) or (htime > mtime) then
	I('pandoc converting '  .. l .. ' -> ' .. l:sub(1, -4) .. 'md')
os.execute('cp ' .. l .. ' ' .. l .. '_ORIGINAL0')
	-- Open the HTM files and do the initial cleanups, then pandoc them.
	h = io.open(l, 'r')
	if nil ~= h then
	    local body = h:read('*a') ; h:close()
writeString(l .. '_ORIGINAL1', body)
	    if 'Foswiki' == l:sub(1, 7) then
		-- Strip out the actual content.
		local beg, en = RE.find(body, [['<div id="patternMainContents">']])	if nil ~= beg then body = body:sub(en + 1)  end
		      beg, en = RE.find(body, [['<div class="patternContent">']])	if nil ~= beg then body = body:sub(en + 1)  end
		      beg, en = RE.find(body, [['<div class="foswikiTopic">']])	if nil ~= beg then
		    if ' -- ' == body:sub(en + 1, en + 4) then
		        beg, en = RE.find(body, '[%nl]', en + 4)
		        body = body:sub(en + 1)
		    end
		end
		      beg, en = RE.find(body, [['<div class="patternInfo">']])							if nil ~= beg then body = body:sub(1, beg - 1) end
--		      beg, en = RE.find(body, [['<div class="foswikiForm foswikiFormStep">']])					if nil ~= beg then body = body:sub(1, en + 1) end
		      beg, en = RE.find(body, [['<div class="foswikiAttachments foswikiFormStep" style="overflow:auto">']])		if nil ~= beg then body = body:sub(1, beg - 1) end
		      beg, en = RE.find(body, [['<div class="foswikiSearchResultsPager">']])					if nil ~= beg then body = body:sub(1, beg - 1) end
		-- Some clean ups.
		local result = RE.compile( [[{~
 (
  {'class="foswikiCurrentTopicLink"'}     -> blank /
  {'class="foswikiNewLink"'}     -> blank /
  {"<span class='foswikiSmall'><a href='/bin/edit/Main/" ([^;action=form])* ";action=form'>edit</a></span>"}           -> blank /
  {" -- "}                       -> '-noComment-' /
--  {"-- " ([^%nl])* }             -> blank /
  {'<div class="foswikiTopic">'} -> blank /
  {'rel="nofollow"'}             -> blank / {"rel='nofollow'"}             -> blank /
  {"target='_blank'"}            -> blank /
  {"</div>" ([%nl])* }           -> blank /
--  {'style="' ([^"])+ '"'}        -> blank / {"style='" ([^'])+ "'"}        -> blank /
  .
 )* ~}]],   { blank = function(a) return '' end } ):match(body)
		body = result
--	        body = RE.gsub(body, [=[{"<!-- ".*"-->"}]=], '')	-- FIXME
	        local here = 1
	        beg, en = RE.find(body, [['https://fos.wiki.devuan.org/']], here)
	        while nil ~= beg do
		    here = beg + 1
		    local beg0, en0
		    local url = nil
		    if '"' == body:sub(beg - 1, beg - 1) then
			beg0, en0 = RE.find(body, [['"']], en)
			url = body:sub(en + 1, en0 - 1)
		    end
		    if "'" == body:sub(beg - 1, beg - 1) then
			beg0, en0 = RE.find(body, [["'"]], en)
			url = body:sub(en + 1, en0)
		    end

		    if nil ~= url then
			if ('pub/' == url:sub(1, 4)) then
-- FIXME? - evil hack?
			    url = 'Foswiki/' .. url
--D('FOSWIKI HTM ' .. url)
			else
			    url = nil
			end
		    end
--D('HTM0 ' .. body:sub(beg, en + 84) .. ' \t\t')
		    beg, en, body, here = commonLinky(l, body, 'https://fos.wiki.devuan.org/', url, beg, en, beg0, en0, 1)
--if nil ~= en then D('HTM1 ' .. body:sub(beg, en + 84) .. ' \t\t') end
--[=[
		if nil == url then
		    W('OOPS! unknown linky  - @' .. l .. '\t\t\t' .. body:sub(beg - 9, en) .. ' ' .. body:sub(en + 1, en0))
		else
--		    I('   linky  - @' .. l .. '\t\t\t' .. body:sub(beg - 9, en) .. ' ' .. body:sub(en + 1, en0) .. ' -> ' .. url)
		    local md = readMdMd(url, {})
--		    if nil ~= md then
			if nil ~= md.realURL then url = md.realURL end
--		    end
		    body = body:sub(1, beg - 1) .. url .. body:sub(en0 + 1)
		    here = here + #url
		end
		beg, en = RE.find(body, [['https://fos.wiki.devuan.org/']], here)
]=]
		end

		writeString(l .. '_NEW', body)
	    elseif 'PmWiki'  == l:sub(1, 6) then
		local beg, en = RE.find(body, [['<!--PageText-->']])	if nil ~= beg then body = body:sub(en + 2)  end
		      beg, en = RE.find(body, [["div id='wikitext'>"]])	if nil ~= beg then body = body:sub(en + 2)  end
		      beg, en = RE.find(body, [["<div id='printfoot'>"]])		if nil ~= beg then body = body:sub(1, beg - (2 + 9)) end	-- There's a </div> to get rid of to.
		      beg, en = RE.find(body, [['<!--HTMLFooter-->']])		if nil ~= beg then body = body:sub(1, beg - 2) end
		local result = RE.compile( [[
{~
 (
  {"class='categorylink'"}       -> blank /
  {"class='createlink'"}         -> blank /
  {"class='createlinktext'"}     -> blank /
  {"class='escaped'"}            -> blank /
  {"class='diffmarkup'"}         -> blank /
  {"class='selflink'"}           -> blank /
  {"class='urllink'"}            -> blank /
  {"<div class='vspace'></div><hr /> <a class='wikilink' href='https://wiki.devuan.org?n=Profiles." .* ([%nl])* } -> blank /
  {"<a class='selflink' href='https://wiki.devuan.org?n=Profiles." .* ([%nl])* } -> blank /
  {"<div class='vspace'></div><hr />"} -> blank /
  {"<div class='vspace'></div>"} -> blank /
  {"class='wikilink'"}           -> blank /
  {'rel="nofollow"'}             -> blank /  {"rel='nofollow'"}             -> blank /
  {"target='_blank'"}            -> blank /
--  {'style="' ([^"])+ '"'}        -> blank / {"style='" ([^'])+ "'"}        -> blank /
  {"<span class='hlt " {([a-z])+} "'></span><pre" }  -> "<pre class='%2'" /
  .
 )* ~}]],   { blank = function(a) return '' end } ):match(body)
		body = result
--	    body = RE.gsub(body, [=["<a  " {([^ >])+} " >"]=], "<a %1>")
-- DONE? - <span class='hlt html'></span><pre  style='background-color: #cc00ff;' class='escaped'>   ...  lines of HTML code   ...   </pre>
--		most of the time I'll see   <pre class='escaped'>
--		My own looking glass has several.
--		Foswiki                     <pre class='bash'>
--		CommonMark->HTML  ---lua    <pre><code class="language-lua">                        ..............................  </code></pre>
--						Seems to be the spec way of doing it.
--		most of the time I'll see   <pre><code>

		here = 1
		beg, en = RE.find(body, [["'https://wiki.devuan.org/"]], here)
		while nil ~= beg do
		    here = beg + 1
		    local beg0, en0 = RE.find(body, [["'"]], en)
-- FIXME? - This might be working around a bug elsewhere.
		    if "'" == body:sub(en0, en0) then en0 = en0 - 1 end
		    local url = body:sub(en + 1, en0)
		    if '?n=' == url:sub(1, 3) then
			url = url:sub(4):gsub('[%a]+%.([%a-]+)', '%1_pm.HTML')
		    elseif ("'" == url) or ('uploads/' == url:sub(1, 8)) then
-- FIXME - evil hack?  Yep, evil hack, need to know the depth of the source, which isn't here.
			url = 'PmWiki/' .. url
		    else
			url = nil
		    end
--D('HTM0 ' .. body:sub(beg, en + 84) .. ' \t\t')
		    beg, en, body, here = commonLinky(l, body, "'https://wiki.devuan.org/", url, beg, en, beg0, en0, 0)
--if nil ~= en then D('HTM1 ' .. body:sub(beg, en + 84) .. ' \t\t') end
		end

		writeString(l .. '_NEW', body)
	    end
	end

	os.execute('pandoc --wrap=preserve -f html -t commonmark_x --self-contained ' .. l .. '_NEW' .. ' >' .. l:sub(1, -4) .. 'md')
    end
end

if '.' ~= Folder then
    for l in io.popen('find -L . -name "*.md" -type f,l -printf "%P\n"'):lines() do
	toFile(l:gsub('%.md$', ''))
    end
end

-- Can add in a distant folder to, for putting it's results in the current folder.
for l in io.popen('find -L ' .. Folder .. ' -name "*.md" -type f,l -printf "%P\n"'):lines() do
    local n = l:gsub('%.md$', '')
    if nil == Files[n] then toFile(n) end
end


-- Gotta figure out all the files and subs first.  File and sub metadata comes along for the ride, coz we need them later.
local NewMeta = {}
for name, file in pairs(Files) do
    local bitter, path = '', ''
    local bits, bit = file.bits, file.bit
    local ln = #bits
    local body, metadata = '', {}

    -- Go through our bits, construct Subs with bits.
    if ln > 0 then bitter = bits[1] end
    if '' ~= bitter then Subs[''].subs[bitter] = bitter end	-- "bitter end" was entirely by accident, I'm keeping it.  B-)
    for i, d in ipairs(bits) do
	if '' ~= path then path = path .. '/' end
	path = path .. d
	toSub(path)
	if i < ln 		then
	    Subs[path].subs[bits[i + 1]] = bits[i + 1]
	    table.remove(Subs[path].bits, #bits)
	end
    end

    if '.md' == name:sub(-3, -1) then
	-- This is a metadata only file, no content, stash the matadata.

	metadata = readMdMd(name, metadata)
	if '.md' == name                          then toSub(path, 'metadata', metadata)
	elseif '/.md' == name:sub(-4, -1) then toSub(path, 'metadata', metadata)
--	else                                           toFile(name:sub(1, -4), 'metadata', metadata)
	else						NewMeta[name:sub(1, -4)] = metadata	-- Coz we can't add to Files here.
	end
	Files[name] = nil
    end
end

-- FIXED - Lua doesn't like modifying the thing you are pair()ing, like we want to do in the last loop.
for name, file in pairs(NewMeta) do
    if nil == Files[name] then toFile(name) end
    for k, v in pairs(file) do
	if nil == Files[name].metadata[k] then Files[name].metadata[k] = v end
    end
end

-- Fix up subs now we have all the file bits.
for name, file in pairs(Files) do
    if '.md' ~= name:sub(-3, -1) then
	table.insert(Subs[file.path].files, file.bit)
    end
end

-- Find empty subs.
for name, sub in pairs(Subs) do
    if 0 == #sub.files then
	W('EMPTY ' .. name)
	h = io.open(name .. '/index.md', 'w')
	if nil ~= h then
	    h:write('This folder has no files.')
	    h:close()
	else
	    E("Can't open " .. name .. '/index.md for writing.')
	end
    end
end


---------------------------------------------------------------------------------
-- These functions assume the above file and sub scan has completed.

-- Which page in this folder should we show?
-- NOTE - only looking for the .md files we scanned for before, any stray HTML, html, HTM, and htm files will get ignored.
local whichPage = function(f)
    local fl = ''
    if nil ~= Subs[f] then
	if nil ~= Subs[f].whichPage then return Subs[f].whichPage end
	if nil ~= Subs[f].files then
	    if 1 == #(Subs[f].files) then	fl = Subs[f].files[1] else
		-- Standard files to search for.
		for i, v in ipairs{'about', 'readme', 'index', 'homepage', 'mainpage', 'webhome'} do
		    for j, w in ipairs(Subs[f].files) do
			if v == w:lower() then
			    fl = w
			    break
			end
		    end
		    if '' ~= fl then break end
		end
		-- If nothing else, just grab the first one.
		if ('' == fl) and (nil ~= Subs[f].files[1]) then fl = Subs[f].files[1] end
	    end
	end
    end
    if '' ~= fl then fl = fl .. '.HTML' ; Subs[f].whichPage = fl end
    return fl
end


-- Figure out the original title and link for the original wiki.
local whichWiki = function(metadata)
    local title, link = '', ''
    if 'PmWiki'  == metadata.ogWiki then
	title = metadata.ogBase .. '.'    .. metadata.ogFile
	link  = metadata.ogURL  .. '/?n=' .. metadata.ogBase .. '.' .. metadata.ogFile
    end
    if 'Foswiki' == metadata.ogWiki then
	title = metadata.ogBase .. '/'    .. metadata.ogFile
	link  = metadata.ogURL  .. '/'    .. metadata.ogBase .. '/' .. metadata.ogFile
    end
    return title, link
end


-- Calculate a link from the source folder to the destination folder.
local linkFrom = function(source, dest)
    -- Evil hacks!
    if 'Profiles' == dest then dest = 'PmWiki/Profiles' end
    if 'Onefang'  == dest then dest = 'PmWiki/Onefang' end
    if 'Tiki'     == dest then dest = 'PmWiki/Tiki' end

    if source == dest then return '' end
    local depth = 0
    local lnk = ''
    if source ~= dest then
	if nil == Subs[source] then
--	    W('!!!! No idea where to find source ' .. source)
	    return 'DUNNO'
	end
	if nil == Subs[dest] then
	    if dest == Subs[source].bit then
		return ''
	    else
--		W('!!!! No idea where to find dest   ' .. dest .. ' from ' .. Subs[source].path .. ' / ' .. Subs[source].bit)
		return 'DUNNO'
	    end
	end
	local s = Subs[source].bits
	local d = Subs[dest].bits
	local sl = #s
	local dl = #d

	if 0 == dl then
	    depth = sl
	else
	    for i, v in ipairs(s) do
		if (nil == d[i]) or (v ~= d[i]) then
		    depth = i
		    break
		end
	    end
	end
	-- depth is where they DON'T match.
	local m = depth - 1
	if 0 > m then m = 0 end
	lnk = string.rep('../', sl - m)
	if 0 ~= (m + 1) then lnk = lnk .. table.concat(d, '/', m + 1, dl) end
    end
    return lnk
end



---------------------------------------------------------------------------------
-- More of this actually doing things nonsense.

-- Create an "everything" page, for URL links to every file.HTML.
local Bdy = '# All the pages\n\n| page | original page | last edited UTC | \n| --------- | ------- | --------------- | '
Pages = {}
for name, file in pairs(Files) do
    local metadata = derefTable(Files[name].metadata, true)
    if ('everything' ~= name) then
	local ln, fw, pw, ts = 'DUNNO', '', '', ''
	local title, link = whichWiki(metadata)
	link = link:gsub('https://', 'HTTPS://')	-- Prevent this one from being converted.
	if 'PmWiki'  == metadata.ogWiki then pw = 'PmWiki  [' .. title .. '](' .. link .. ')' end
	if 'Foswiki' == metadata.ogWiki then fw = 'Foswiki [' .. title .. '](' .. link .. ')' end
	if nil       ~= metadata.timestamp then ts = metadata.timestamp end
	if nil ~= file.bit   then ln = file.bit
	end
	table.insert(Pages, '\n| [' .. name .. '](<' .. name .. '.HTML>) | ' .. fw .. '  ' .. pw .. ' | ' .. ts .. ' |')

	-- Track our external links.
	if (nil ~= metadata.ogBase) and (nil ~= metadata.ogFile) then
	    local n = metadata.ogBase
	    if 'PmWiki'  == metadata.ogWiki then n = n .. '.' else n = n .. '/' end
	    xLinks[n .. metadata.ogFile] = file.path
	end
    end
end
table.sort(Pages, function(a, b) return (a:lower() < b:lower())  end)
for i, f in ipairs(Pages) do
    Bdy = Bdy .. f
end
h = io.open('everything.md', 'a+')
if nil ~= h then
    h:write(Bdy)
    h:close()
else
    E"Can't open everything.md for writing."
end
toFile('everything', 'body', Bdy)


-- Loop through Subs, doing whichPage and inheritance.
-- It gets to testing/even/deeper BEFORE it gets to testing/even sometimes.  So sort them.
SUBS = {}
for name, sub in pairs(Subs) do
    table.insert(SUBS, sub)
end
table.sort(SUBS, function(a, b) return (a.path:lower() < b.path:lower())  end)
for n, sub in pairs(SUBS) do
    local name = sub.path
    sub.whichPage = whichPage(name)
    local metadata = sub.metadata
    for i, s in pairs(sub.subs) do
	local nm = i
	if '' ~= name then nm = name .. '/' .. i end
	for k, v in pairs(metadata) do
	    if nil == Subs[nm].metadata[k] then
		if ('favicon' == k) or ('logo' == k) then
		    Subs[nm].metadata[k] = linkFrom(nm, name) .. v
		else
		    if 'hidden' ~= k then	-- Don't inherit hidden.
			Subs[nm].metadata[k] = v
		    end
		end
	    end
	end
    end
end

-- Files inheritance.
for name, file in pairs(Files) do
    if '' ~= file.body then
	local mdata = Subs[file.path].metadata
	for k, v in pairs(mdata) do
	    if nil == file.metadata[k] then
		Files[name].metadata[k] = v
	    end
	end
    end
end


---------------------------------------------------------------------------------
-- Setup the lunarmark stuff.
local LunamarkOpts = {
    layout='compact',
-- This list is copied from the lunamark source code, until I discover a way to discover it.  The descriptions are useful to.
    containers=false,            -- Put sections in containers (e.g. div or section tags)
    slides=false,                -- Like containers, but do not nest them
    startnum=true,               -- Start number of an ordered list is significant
    smart=false,                 -- Smart typography (quotes, dashes, ellipses)
    preserve_tabs=true,          -- Don't expand tabs to spaces
    notes=true,                  -- Footnotes
    inline_notes=true,           -- Inline footnotes
    definition_lists=true,       -- Definition lists
    citations=true,              -- Citations
    citation_nbsps=true,         -- Turn spacing into non-breaking spaces in citations
    fenced_code_blocks=true,     -- Fenced code blocks
    lua_metadata=true,           -- Lua metadata
    pandoc_title_blocks=true,    -- Pandoc style title blocks
    hash_enumerators=true,       -- may be used as ordered list enumerator
    require_blank_before_blockquote=false,
    require_blank_before_header=false,
    require_blank_before_fenced_code_block=false,
    fancy_lists=true,            -- Pandoc style fancy lists
    task_list=true,              -- GitHub-Flavored Markdown task list
    strikeout=true,              -- Strike-through with double tildes
    mark=true,                   -- Highlight with double equals
    subscript=true,              -- Subscripted text between tildes
    superscript=true,            -- Superscripted text between circumflexes
    bracketed_spans=true,        -- Spans with attributes
    fenced_divs=true,            -- Divs with attributes
    raw_attribute=true,          -- Raw pass-through on code elements
    fenced_code_attributes=true, -- Fenced code block attributes
    link_attributes=true,        -- Link attributes
    pipe_tables=true,            -- PHP Markdown Extra pipe table support
    table_captions=true,         -- Table caption syntax extension
    header_attributes=true,      -- Header attributes
    line_blocks=true,            -- Line blocks
    escaped_line_breaks=true,    -- Pandoc-style escaped hard line breaks
}
local Writer = Lunamark.writer.html5.new(LunamarkOpts)
-- Can override the various writer functions, there's something for each of the basic HTML elements.
local lunaLinky = function(url, lab, tit)		-- Fix up the links.
    local done = false
    if url:sub(1, 4) == 'HTTP' then
	if url:sub(1, 5) == 'HTTPS' then url = 'https' .. url:sub(6) else url = 'http' .. url:sub(5) end
    end
    local u = url:lower()
    if u:sub(1, 7) == 'http://'  then u = u:sub(8) end
    if u:sub(1, 8) == 'https://' then u = u:sub(9) end
    if u:sub(1,25 ) == 'wiki.friendsofdevuan.org/' then
        u = u
    elseif u:sub(1, 15) == 'wiki.devuan.org' then
	u = u
--    else
--print('************************ ' .. url)
    end
    if ('https://wiki.devuan.org/' ~= url) and ('https://fos.wiki.devuan.org/' ~= url) then
	-- TODO - This might be covering up a bug elsewhere.
	if '/Main/' == url:sub(1, 6) then
	    local link = linkFrom(Context.path, 'Foswiki/Main')
	    if '' == link then
		url =                url:sub(7) .. '.HTML'
	    else
		url = link .. '/' .. url:sub(7) .. '.HTML'
	    end
	end
	if '/System/' == url:sub(1, 8) then
	    url = 'https://fos.wiki.devuan.org' .. url
	end
	for i, p in ipairs{'https://wiki.devuan.org/?n=', 'https://wiki.devuan.org?n=', 'PmWiki/uploads/', 'Foswiki/pub/', 'https://fos.wiki.devuan.org/'} do
	    if p == url:sub(1, #p) then
		local ur = url:sub(#p + 1)
-- TODO - could probably replace some of this mess with RE.gsub() and friends.  Meh, it works.
		local f4, f5, tk1 = ur:find('?', 1, true)
		if fail ~= f4 then
		    local u = ur:sub(1, f4 - 1)
		    ur = u
		end
		local md

		if ('fos' == p:sub(9, 11)) or ('Fos' == p:sub(1, 3)) then
		    md = readMdMd('Foswiki/' .. ur .. '.md', {})
		else
		    md = readMdMd('PmWiki/' .. ur:gsub('%.', '/', 1) .. '.md', {})
		end
		if (nil ~= md) and (nil ~= md.realURL) then	url = md.realURL end

		if ('https://fos.wiki.devuan.org/bin/' ~= url:sub(1, 32)) and ('https://fos.wiki.devuan.org/System/' ~= url:sub(1, 35)) then
		    local xlnk = xLinks[ur:gsub('%..*', '', 1)]
		    if nil == Context.path then
			url = ur:gsub('%.', '/', 1)
		    else
			if nil == xlnk then xlnk = string.gsub(ur:gsub('%..*', '', 1), '/.*', '', 1) end
			if '' ~= Context.path then xlnk = linkFrom(Context.path, xlnk) end
			if '/' == xlnk:sub(1, 1) then xlnk = xlnk:sub(2) end
			if ('' ~= xlnk) and ('/' ~= xlnk:sub(-1)) then xlnk = xlnk .. '/' end
			if 'DUNNO/' == xlnk then E('OOPS! page not found - @' .. Context.path .. ' / ' .. Context.bit .. '\t' .. url .. ' -> ' .. xlnk .. ' ' .. ur:gsub('.*%.', '', 1) .. '.HTML') end
		    end
--		if (nil ~= md) and (nil ~= md.realURL) then	url = md.realURL
--		else
								url = xlnk .. ur:gsub('.*%.', '', 1)
--		end
		    if 'PmWiki/uploads/' == p then
			url = '../../' .. p .. ur:gsub('%.', '.', 1)
		    elseif 'Foswiki/pub/' == p then
			url = '../../' .. p .. ur
		    else
			url = url .. '.HTML'
		    end
		end
		done = true
	    end
	end
    end
    if (url:sub(-4) ~= '.png') and (url:sub(-5) ~= '.HTML') then url = url .. '.HTML' end
    if not done then
	-- TODO - Should check if this came from DocuWiki in the first place, AND double check this is for img src.
	if url:sub(1, 1) == '/' then
	    local p = url
	    local cnt = 0
	    for j = 1, #p do
		if '/' == p:sub(j, j) then cnt = cnt + 1 end
	    end
--	    if p:sub(1, 9) ~= 'DocuWiki/' then cnt = cnt + 1 end
	    if url:sub(-4) == '.png' then cnt = cnt + 1 end
	    url = string.rep('../', cnt) .. 'DocuWiki/pages' .. p
	elseif url:sub(1, 37) == 'https://friendsofdevuan.org/doku.php/' then
	    url = 'DocuWiki/pages' .. url:sub(37):gsub(':', '/')
	end
    end
    return url:gsub('//DocuWiki//DocuWiki//', '/DocuWiki/')
end

function Writer.header(s, level)
    local text = Lunamark.util.rope_to_string(s)
-- FIXME - Work around a bug in Lunamark?
    text = RE.gsub(text, '{[\\]}', '')
    return '<h' .. level .. ' id="' .. RE.gsub(text, '{[ ]}', '_') .. '">' .. text .. ' <a style="font-size: 0.42em;" href="#top">🔼</a></h' .. level .. '>'
end
local OgWriterLink = Writer.link	-- So we can call the original from within mine, we are just changing the URL.
function Writer.link(lab, url, tit)
    return OgWriterLink(lab, lunaLinky(url, lab, tit), tit)
end
local OgWriterImage = Writer.image
function Writer.image(lab, url, tit)
    return OgWriterImage(lab, lunaLinky(url, lab, tit), tit)
end

local Parse = Lunamark.reader.markdown.new(Writer, LunamarkOpts)


---------------------------------------------------------------------------------
-- Loop through the files we found and actually create their HTML files.
for name, file in pairs(Files) do
    local body, metadata = Files[name].body, derefTable(Files[name].metadata, true)
    local bits, bit = Files[name].bits, Files[name].bit
    local ln = #bits
    local result = ''

    if '' ~= body then
	-- Figure out this pages trail links.
	metadata.home = linkFrom(file.path, '') .. Subs[''].whichPage
	metadata.trail = ''
	for i, b in ipairs(bits) do
	    local p = table.concat(bits, '/', 1, i)
	    if i < #bits then
		metadata.trail = metadata.trail .. '<a href="' .. linkFrom(file.path, p) .. Subs[p].whichPage .. '">' .. b .. '</a> &nbsp; &#x1f463; '
		linkFrom(file.path, table.concat(bits, '/', 1, i))
	    else
		metadata.trail = metadata.trail .. ' ' .. b
	    end
	end

	-- Figure out this pages header links.
	metadata.header = ''
	subs = {}
	for i, f in pairs(Subs[file.path].subs) do
	    table.insert(subs, f)
	end
	table.sort(subs, function(a, b) return (a:lower() < b:lower())  end)
	for i, f in ipairs(subs) do
	    local pth = file.path
	    if '' ~= file.path then pth = file.path .. '/' end
	    if 'true' ~= Subs[pth .. f].metadata.hidden then
		metadata.header = metadata.header .. '<a href="' .. f .. '/' .. whichPage(pth .. f) .. '">' .. f .. '</a> &nbsp; &#128194; '
	    end
	end

	-- Figure out this pages menu links.
	metadata.menu = ''
	if nil == metadata.title then metadata.title = bit end
	if nil ~= Subs[file.path].files then table.sort(Subs[file.path].files, function(a, b) return (a:lower() < b:lower())  end)  end
	for i, f in ipairs(Subs[file.path].files) do
	    local title, url = nil, nil
	    if '' == file.path then
		title = Files[f].metadata.title
		url   = Files[f].metadata.URL
	    else
		title = Files[file.path .. '/' .. f].metadata.title
		url   = Files[file.path .. '/' .. f].metadata.URL
	    end
	    if nil == title then title = f end


	    if bit == f then
					metadata.menu = metadata.menu .. '<p>' .. title .. '</p>'
		for j, g in ipairs(file.headers) do
			local beg, en = RE.find(g, [['{']])
			if nil ~= beg then
			    g = g:sub(1, beg - 2)
			end
		    local h = string.sub(RE.gsub(g, '{[#]}', ''), 2)
		    local l = g:len() - h:len()
		    g = h
		    h = RE.gsub(h, '{[ ]}', '&nbsp;')
-- FIXME - Work around a bug in Lunamark?
		    g = RE.gsub(g, '{[\\]}', '')
		    h = RE.gsub(h, '{[\\]}', '')
-- FIXME - if it's a linky, strip off the URL part.  The Wiki audit has such things.
					metadata.menu = metadata.menu .. '<p>' .. string.rep('&nbsp;', l) .. '<a style="font-size: 0.80em;" href="#' .. RE.gsub(g, '{[ ]}', '_') .. '">' ..  h .. '</a></p>'
		end
	    else
		if nil ~= url then	metadata.menu = metadata.menu .. '<p><a href="' .. url .. '">'      .. title .. ' &#9757;</a></p>'
		else
		    local pth = file.path
		    if '' ~= pth then pth = pth .. '/' end
		    -- Don't include any left over .md.md files, so don't do this if f.md doesn't exist.
		    local a, e = io.open(pth .. f .. '.md' , 'r')
		    if nil ~= a then
			a:close()
					metadata.menu = metadata.menu .. '<p><a href="' .. f   .. '.HTML">' .. title .. '</a></p>'
		    end
		end
	    end
	end

	-- Figure out this pages footer links.
	local temp = ''
	metadata.footer = ''
	if nil == metadata.pagehistory then
	    if 'Foswiki'  == metadata.ogWiki then metadata.pagehistory =  metadata.ogURL .. '/bin/oops/' .. metadata.ogBase .. '/' .. metadata.ogFile  .. '?template=oopshistory' end
	    if 'PmWiki'   == metadata.ogWiki then metadata.pagehistory =  metadata.ogURL .. '/?n='       .. metadata.ogBase .. '.' .. metadata.ogFile  .. '?action=diff' end
	else
	    temp = '/' .. name .. '.md'
	end
	if nil ~= metadata.pagehistory then metadata.history = '<p>Page&nbsp;<a href="' .. metadata.pagehistory .. temp .. '">history</a></p>' else
	    metadata.history = ''
	end
	if nil ~= metadata.sourcecode	then metadata.footer = '<a href="' .. metadata.sourcecode	.. '">source code</a>'    end
	if nil ~= metadata.feedatom		then metadata.footer = '<a href="' .. metadata.feedatom		..   '">atom feed<img src="feed-icon-14x14.png"></img></a> &nbsp; &nbsp; ' .. metadata.footer    end
	if metadata.footer ~= '' then metadata.footer = 'Web site ' .. metadata.footer end
	-- Add a link to the original page.
	if nil ~= metadata.ogURL then
	    local title, link = whichWiki(metadata)
	    link = link:gsub('https://', 'HTTPS://')	-- Prevent this one from being converted.
-- TODO - wrap "edit" in a link to actually edit it. PmWiki "?action=edit"  Foswiki "https://fos.wiki.devuan.org/bit/edit/" .. page .. "?t=" .. 10 digit random number?
	    local edit = 'T'
	    if 'PmWiki'  == metadata.ogWiki then edit = 'Maybe you can <a href="' .. link .. '?action=edit">edit</a> t' end
--	    if 'Foswiki' == metadata.ogWiki then edit = '' end
	    metadata.footer = edit .. 'he <a href="' .. link .. '">original page</a>. &nbsp; ' .. metadata.footer
	end
	metadata.footer = '<p>' .. metadata.footer .. '</p>'

	-- Do our own metadata replacement, it's simple and works better.
	local temp = Template
	-- Toss the body in first, so the scan can deal with it to.
	-- NOTE - this is where we actually parse the markup into HTML.
	Context = file
	body = RE.gsub(body, '{[%nl]^1[%a]+}[.]^1 ', '%1$dot$ ')	-- Coz otherwise stray . trip up the list detection.
	local bd, md = Parse(body)		-- The md is a table of extracted metadata, not likely to be any, and we wont do anything with it.
	bd = RE.gsub(bd, '{[%]}', '$perc$')	-- Coz otherwise stray % trip up the capture part.
	temp = RE.gsub(temp, '"$body$"', bd)
	-- The actual metadata replacement.
	result = RE.compile ('{~ ({[$][A-Za-z_]+[$]} -> meta / .)* ~}',
	{
	    meta = function(a)
		a = a:sub(2, -2)
		local md = metadata[a]
		if nil == md then
		    md = GlobalMetaData[a]
		    if nil == md then
			md = a
		    end
		end
		return md
	    end
	} ):match(temp)

	-- Write the file.
	if '' ~= result then
	    writeString(name .. '.HTML', result)
--	    D('From ' .. name .. '.md -> ' .. base)
	end
    end
end


