require("luamods/command")
require("luamods/layout")
require("luamods/cgi")
require("config/software_conf")

priv = db.getPriv(cgi.cookie.userID) or 1

rtr = ""

header = layout.getHeader()
footer = layout.getFooter()

function parsePackages()
    rtr = command.ex(software_conf.opkg_installed_pack)
    
    if (rtr == nil) then rtr = "" end
    packages = {}
    for line in rtr:gmatch("(.-\n)") do
        name,version = line:match("(.-)%s+(.-)\n")
        if (name ~= nil) and (version ~= nil) then
            package = {}
            package.name = name
            package.version = version
            table.insert(packages, package)
        end
    end
    return packages, #(packages)
end

content = [[
                    <div id="info">
                        <div style="background:url(images/software.png); background-size:32px; background-repeat:no-repeat; background-position: 20px center;">
                            <center><h1>Software - Installed Packages</h1></center>
                        </div>
                    </div>
]]

pkgs, pkgCount = parsePackages()

if (pkgCount > 0) then
    content = content .. [[
                    <div>
                        <b><br>
                        <center>
                            This is a list of all the currently installed software packages.<BR>
                            Click on the package names to manage individual software packages.</b>
                        </center><br>
                        <a href="software_export_installed.lua">Export list of installed packages as CSV</a><br><br>
                        <table class="onetwo" border="1">
                            <tr>
                                <th>Package name</th>
                                <th style="white-space:nowrap;" >Version</th>
                            </tr>
]]
    for num, package in pairs(pkgs) do
        content = content .. [[
                            <tr>
                                <td><a href="software_pkg_info.lua?name=]]..package.name..[[&version=]]..package.version..[[&installed=installed&upgrade=up-to-date">]]..package.name..[[</a></td>
                                <td style="white-space:nowrap;">]]..package.version..[[</td>
                            </tr>
]]                            
    end
    content = content .. [[
                        </table><br>
                        <a href="software_export_installed.lua">Export list of installed packages as CSV</a>

                    </div>
]]
else
    content = content .. [[
                <div id="info">
                    <center>
                        <h2><img src="images/warning.png"/> No installed packages</h2>
                        Either the package manager (opkg-cl) is not responding,<br>
                        or there are no known installed packages.
                    </center>
                </div>
]]
end

print(header .. content .. footer)
