aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/notYetAnotherWiki.lua
blob: 1cea01b0d65f7ff54d3ae8779791225d9034fd9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
#!/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


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

local GlobalMetaData = {
    dlr = '$', 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')
    h:close()
else
    print('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 '/' == string.sub(l, j, j) then
	    table.insert(bits, string.sub(l, last, j - 1))
	    last = j + 1
	end
    end
    return bits, string.sub(l, 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' ~= string.sub(name, -3, -1) then
	h = io.open(name .. '.md', 'r')
	if nil ~= h then
--	    print('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
--	    print('Could not open ' .. name .. '.md')
	    return {}
	else
	    for l in h1:lines() do
		for k, v in string.gmatch(l, "(%w+)%s*=%s*(.+)") do 
		    if nil == v then
			print(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
--		    print('OOPS! unknown linky  - @' .. l .. '\t\t\t' .. string.sub(body, beg - 9, en) .. ' ' .. string.sub(body, en + 1, en0))
		else
		    local md = readMdMd(url, {})
--		    if nil ~= md then
			if nil ~= md.realURL then url = md.realURL end
--		    end
		    body = string.sub(body, 1, beg - bump) .. url .. string.sub(body, en0 + 1)
		    here = here + string.len(url)
	        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
    print("Can't open everything.md for writing.")
end

-- Scan the subdirectories looking for our files.
local Directory = arg[1]
toSub('')
if nil == Directory then Directory = '.' end

-- Sort out realURL for symlinked .md.md files.
for l in io.popen('find -L ' .. Directory .. ' -name unsorted -prune -o -name "*.md.md" -xtype l -printf "%P\n"'):lines() do
    local metadata = readMdMd(string.sub(l, 1, -4), {})
-- FIXME - if this already exists, compare the timestamps, most recent wins.
    metadata.realURL = string.sub(l, 1, -7)
    local a, e = io.open(l, 'w')
    if nil == a then print('Could not open ' .. l .. ' - ' .. e) else
	for k, v in pairs(metadata) do
	    a:write(k .. '=' .. v .. '\n')
	end
	a:close()
    end
end

-- Clean up unsorted.
for l in io.popen('find -L ' .. Directory .. ' -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()
		os.execute('rm ' .. unsort .. tp .. '.*')
	    end
	end
    end
end

-- Look for copied pages from the other wikis.
for l in io.popen('find -L ' .. Directory .. ' -name "*.HTM" -type f,l -printf "%P\n"'):lines() do
-- TODO - 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 " .. string.sub(l, 1, -4) .. "md +%s 2>/dev/null"):read('l')
    if (nil == mtime) or (htime > mtime) then
	print('pandoc converting '  .. l .. ' -> ' .. string.sub(l, 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' == string.sub(l, 1, 7) then
		-- Strip out the actual content.
		local beg, en = RE.find(body, [['<div id="patternMainContents">']])	if nil ~= beg then body = string.sub(body, en + 1)  end
		      beg, en = RE.find(body, [['<div class="patternContent">']])	if nil ~= beg then body = string.sub(body, en + 1)  end
		      beg, en = RE.find(body, [['<div class="foswikiTopic">']])	if nil ~= beg then
		    if ' -- ' == string.sub(body, en + 1, en + 4) then
		        beg, en = RE.find(body, '[%nl]', en + 4)
		        body = string.sub(body, en + 1)
		    end
		end
		      beg, en = RE.find(body, [['<div class="patternInfo">']])							if nil ~= beg then body = string.sub(body, 1, beg - 1) end
--		      beg, en = RE.find(body, [['<div class="foswikiForm foswikiFormStep">']])					if nil ~= beg then body = string.sub(body, 1, en + 1) end
		      beg, en = RE.find(body, [['<div class="foswikiAttachments foswikiFormStep" style="overflow:auto">']])		if nil ~= beg then body = string.sub(body, 1, beg - 1) end
		      beg, en = RE.find(body, [['<div class="foswikiSearchResultsPager">']])					if nil ~= beg then body = string.sub(body, 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 '"' == string.sub(body, beg - 1, beg - 1) then
			beg0, en0 = RE.find(body, [['"']], en)
			url = string.sub(body, en + 1, en0 - 1)
		    end
		    if "'" == string.sub(body, beg - 1, beg - 1) then
			beg0, en0 = RE.find(body, [["'"]], en)
			url = string.sub(body, en + 1, en0)
		    end

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

		writeString(l .. '_NEW', body)
	    elseif 'PmWiki'  == string.sub(l, 1, 6) then
		local beg, en = RE.find(body, [['<!--PageText-->']])	if nil ~= beg then body = string.sub(body, en + 2)  end
		      beg, en = RE.find(body, [["div id='wikitext'>"]])	if nil ~= beg then body = string.sub(body, en + 2)  end
		      beg, en = RE.find(body, [["<div id='printfoot'>"]])		if nil ~= beg then body = string.sub(body, 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 = string.sub(body, 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 "'" == string.sub(body, en0, en0) then en0 = en0 - 1 end
		    local url = string.sub(body, en + 1, en0)
		    if '?n=' == string.sub(url, 1, 3) then
			url = string.sub(url, 4):gsub('[%a]+%.([%a-]+)', '%1_pm.HTML')
		    elseif ("'" == url) or ('uploads/' == string.sub(url, 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
--print('HTM0 ' .. string.sub(body, 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 print('HTM1 ' .. string.sub(body, beg, en + 84) .. ' \t\t') end
		end

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

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

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

-- Can add in a distant directory to, for putting it's results in the current directory.
for l in io.popen('find -L ' .. Directory .. ' -name "*.md" -type f,l -printf "%P\n"'):lines() do
    local n = string.gsub(l, '%.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' == string.sub(name, -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' == string.sub(name, -4, -1) then toSub(path, 'metadata', metadata)
--	else                                           toFile(string.sub(name, 1, -4), 'metadata', metadata)
	else						NewMeta[string.sub(name, 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' ~= string.sub(name, -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
	print("EMPTY " .. name)
	h = io.open(name .. '/index.md', 'w')
	if nil ~= h then
	    h:write('This directory has no files.')
	    h:close()
	else
	    print("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 directory 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 == string.lower(w) 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 directory to the destination directory.
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
--	    print('!!!! No idea where to find source ' .. source)
	    return 'DUNNO'
	end
	if nil == Subs[dest] then
	    if dest == Subs[source].bit then
		return ''
	    else
--		print('!!!! 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 = string.gsub(link, '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 (string.lower(a) < string.lower(b))  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
    print("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 (string.lower(a.path) < string.lower(b.path))  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)		-- Fix up the links.
    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/' == string.sub(url, 1, 6) then
	    local link = linkFrom(Context.path, 'Foswiki/Main')
	    if '' == link then
		url =                string.sub(url, 7) .. '.HTML'
	    else
		url = link .. '/' .. string.sub(url, 7) .. '.HTML'
	    end
	end
	if '/System/' == string.sub(url, 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 == string.sub(url, 1, #p) then
		local ur = string.sub(url, #p + 1)
-- TODO - could probably replace some of this mess with RE.gsub() and friends.  Meh, it works.
		local f4, f5, tk1 = string.find(ur, '?', 1, true)
		if fail ~= f4 then
		    local u = string.sub(ur, 1, f4 - 1)
		    ur = u
		end
		local md
		if ('fos' == string.sub(p, 9, 11)) or ('Fos' == string.sub(p, 1, 3)) then
		    md = readMdMd('Foswiki/' .. ur .. '.md', {})
		else
		    md = readMdMd('PmWiki/' .. string.gsub(ur, '%.', '/', 1) .. '.md', {})
		end
		if (nil ~= md) and (nil ~= md.realURL) then	url = md.realURL end

		if ('https://fos.wiki.devuan.org/bin/' ~= string.sub(url, 1, 32)) and ('https://fos.wiki.devuan.org/System/' ~= string.sub(url, 1, 35)) then
		    local xlnk = xLinks[string.gsub(ur, '%..*', '', 1)]
		    if nil == Context.path then
			url = string.gsub(ur, '%.', '/', 1)
		    else
			if nil == xlnk then xlnk = string.gsub(string.gsub(ur, '%..*', '', 1), '/.*', '', 1) end
			if '' ~= Context.path then xlnk = linkFrom(Context.path, xlnk) end
			if '/' == string.sub(xlnk, 1, 1) then xlnk = string.sub(xlnk, 2) end
			if ('' ~= xlnk) and ('/' ~= string.sub(xlnk, -1)) then xlnk = xlnk .. '/' end
			if 'DUNNO/' == xlnk then print('OOPS! page not found - @' .. Context.path .. ' / ' .. Context.bit .. '\t' .. url .. ' -> ' .. xlnk .. ' ' .. string.gsub(ur, '.*%.', '', 1) .. '.HTML') end
		    end
--		if (nil ~= md) and (nil ~= md.realURL) then	url = md.realURL
--		else
								url = xlnk .. string.gsub(ur, '.*%.', '', 1)
--		end
		    if 'PmWiki/uploads/' == p then
			url = '../' .. p .. string.gsub(ur, '%.', '.', 1)
		    elseif 'Foswiki/pub/' == p then
			url = '../' .. p .. ur
		    else
			url = url .. '.HTML'
		    end
		end
	    end
	end
    end
    return url
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), tit)
end
local OgWriterImage = Writer.image
function Writer.image(lab, url, tit)
    return OgWriterImage(lab, lunaLinky(url), 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 (string.lower(a) < string.lower(b))  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; '
	    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 (string.lower(a) < string.lower(b))  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 = string.sub(g, 1, beg - 2)
			end
		    local h = string.sub(RE.gsub(g, '{[#]}', ''), 2)
		    local l = string.len(g) - string.len(h)
		    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			metadata.menu = metadata.menu .. '<p><a href="' .. f   .. '.HTML">' .. title .. '</a></p>'
		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</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 = string.gsub(link, '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 = string.sub(a, 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
--	    print('From ' .. name .. '.md -> ' .. base)
	    writeString(name .. '.HTML', result)
	end
    end
end