-- Creates help window links to all *.lua files in your scripts folder.

local glu = glu()
local gp = require "gplus"

local pathsep = glu.getdir("app"):sub(-1)
local numlinks = 0

--------------------------------------------------------------------------------

function GetLuaFiles(dir, level, lines)
    -- recursively traverse given directory looking for *.lua files
    local files = glu.getfiles(dir)
    if files == nil then
        glu.exit("The given directory does not exist:\n"..dir)
    elseif #files == 0 then
        return lines
    else
        table.sort(files)
    end
    local indent = ""
    for i = 1, level do indent = indent.."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" end
    for _, name in ipairs(files) do
        if name:sub(-1) == pathsep then
            -- name is a subdirectory
            lines = lines..indent.."<b>"..name.."</b><br>\n"
            lines = GetLuaFiles(dir..name, level+1, lines)
        else
            -- name is a file
            local fullname = dir..name
            if name:sub(-4) == ".lua" then
                -- create an "open:" link to this script
                lines = lines..indent.."<a href=\"open:"..fullname.."\">"..name.."</a><br>\n"
                numlinks = numlinks + 1
            end
        end
    end
    return lines
end

--------------------------------------------------------------------------------

function ShowHelp(links, dir)
    -- create a html file with given links and show in Glu's help window
    local htmldata = [[
<html><title>Your Scripts</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<body bgcolor="#FFFFCE">
<p>
To run a script, just click on its link.
Or to open the script in your <a href="prefs:file">preferred text editor</a>,
control-click or right-click on its link.
<p>
LINKS
</body></html>
]]
    if numlinks > 0 then
        htmldata = htmldata:gsub("LINKS", "<b>"..dir.."</b><br>\n"..links)
    else
        htmldata = htmldata:gsub("LINKS", "No *.lua files were found in your scripts folder:<br>\n"..dir)
    end

    -- copy the html data to a temporary file
    local htmlfile = glu.getdir("temp").."yourscripts.html"
    local f = io.open(htmlfile,"w")
    if not f then
        glu.exit("Failed to create file:\n"..htmlfile)
    end
    f:write(htmldata)
    f:close()
    glu.help(htmlfile)
end

--------------------------------------------------------------------------------

local yourdir = glu.getdir("scripts")
if yourdir == "" then
    -- nicer not to beep
    glu.note("You need to open Preferences and select the folder with your scripts.")
else
    ShowHelp(GetLuaFiles(yourdir, 1, ""), yourdir)
end
