#!/usr/bin/php-cgi -dcgi.force_redirect=0
<?php
# encoding: utf-8
# api: cgi
# type: output
# category: api
# title: trees API
# description: Simulate GitHub directory listing response
# version: 0.1
# state: beta
# depends: php:sqlite
# config: -
#
# Always outputs complete file list, trunk only.
#


#-- init
include("./fossil_common.php");
#$fn = ltrim($_SERVER["PATH_INFO"], "/");
#print_r($_SERVER);


#-- search
function file_list() {
    return db("
       SELECT uuid, name, mperm, size, MAX(rid)
       FROM blob LEFT JOIN mlink ON blob.rid=mlink.fid
                 LEFT JOIN filename ON mlink.fnid=filename.fnid
       GROUP BY name
       ORDER BY name
       --ORDER BY rid DESC
    ");
}
function trees() {
    $r = [];
    foreach(file_list() as $f) {
        if (empty($f["name"])) {
            continue;
        }
        $r[] = [
            "path" => $f["name"],
            "mode" => decoct($f["mperm"]),
            "type" => "blob",
            "sha" => $f["uuid"],
            "size" => $f["size"],
            "url" => "$_SERVER[FOSSIL_SELF]raw/$f[uuid]?at=$f[name]"
        ];
    }
    return $r;
}
function last_uuid() {
    return db("SELECT uuid FROM blob ORDER BY rid DESC LIMIT 1")[0]["uuid"];
}

#-- output
header("Content-Type: application/json");
print(json_encode([
  "sha" => last_uuid(),
  "url" => "$_SERVER[FOSSIL_SELF]ext/trees",
  "tree" => trees(),
  "truncated" => false
], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES));

