#!/usr/bin/php-cgi -dcgi.force_redirect=0
<?php
# encoding: utf-8
# api: cgi
# type: display
# category: list
# title: Ext/ index
# description: Lists all CGI extensions in the extroot: folder
# version: 0.3
# state: stable
# config: -
#
# Just a glob() and some crude plugin meta extraction.
#
error_reporting(0);

#-- fossil HTML output
function page_md($text) {
    header("Content-Type: text/html; charset=utf-8");
    print <<<EOF
<div class='fossil-doc' data-title='Extensions'>
<style>
 .extensions-index {
    columns: 2;
 }
 .fsl-ext {
    width: 100%;
    display: inline-block;
    background: #1b1b1b;
    border-radius: 5pt;
    box-shadow: 2pt 2pt 3pt #666;
    padding: 10pt 15pt;
    margin: 5pt 2pt;
    color: #ddd;
 }
 .fsl-ext a {
    color: #fe9;
    font-weight: 900;
    font-size: 115%;
 }
 .fsl-ext .version {
    background: #542;
    color: black;
    padding: 2pt 10pt;
    margin-left: 4pt;
    border-radius: 4pt;
 }
 .fsl-ext .right {
    break: both;
    float: right;
    display: block;
    position: relative;
    right: -15pt;
 }
 .fsl-ext .right div {
    padding: 2pt 10pt;
    border-radius: 5pt 0 0 5pt;
    background: #114;
    color: #777;
    margin-bottom: 4pt;
 }
 .fsl-ext .right div.category {
    color: #aaa;
    background: #225;
 }
</style>
$text
EOF;
}

#-- filtered file list
function ls($dir) {
    $ls = [];
    foreach (glob("$dir/*") as $fn) {
        if (is_file($fn) and is_executable($fn) and is_readable($fn)) {
            $ls[] = basename($fn);
        }
    }
    return $ls;
}

#-- rough plugin meta data reading
function meta($fn) {
    $src = file_get_contents($fn, false, NULL, 0, 1024);
    preg_match_all("~^\s{0,2}[#*\/]+\s{0,2}([\w\-]+):\s*(.+)\n~m", $src, $uu);
    $r = array_combine($uu[1], $uu[2]);
    preg_match_all("~^\s*[#*\/]+\s*((?!\w+:|!)\S.+)\n~m", $src, $uu);
    $r["doc"] = implode("\n", $uu[1]);
    return $r;
}

#-- run
page_md("<div class=extensions-index>\n");
foreach (ls(__DIR__) as $fn) {
    $meta = meta($fn);
    $h = "htmlspecialchars";
    $title = $meta["title"] ?: $fn;
    $version = $meta["version"] ?: "-";
    $desc = $meta["description"] ?: $fn;
    $type = $meta["type"] ?: "extension";
    $cat = $meta["category"] ?: "-";
    print <<<EOF

    <div class="fsl-ext $cat" title="{$h($meta['doc'], ENT_QUOTES)}">
        <a href="$_SERVER[FOSSIL_URI]/ext/$fn">$title</a>
        <span class=version>$version</span>
        <span class=right>
          <div class=type>$type</div>
          <div class=category>$cat</div>
        </span>
        <div class=description>{$h($desc)}</div>
    </div>

EOF;
}
    print "</div>";

?>