xquery version "3.0";
(:
    ART-DECOR® STANDARD COPYRIGHT AND LICENSE NOTE
    Copyright © ART-DECOR Expert Group and ART-DECOR Open Tools GmbH
    see https://docs.art-decor.org/copyright and https://docs.art-decor.org/licenses

    This file is part of the ART-DECOR® tools suite.
:)
import module namespace get         = "http://art-decor.org/ns/art-decor-settings" at "art-decor-settings.xqm";

declare %private function local:check-xqueries($path as xs:string) as element()* {
    for $xq in xmldb:get-child-resources($path)
    return 
        if (ends-with($xq, '.xquery') or ends-with($xq, '.xq') or ends-with($xq, '.xqm'))
        then 
            let $xq := concat($path, '/', $xq)
            let $chk := util:compile-query(util:binary-to-string(util:binary-doc($xq)), $path)
            return <checked xquery="{$xq}">{$chk}</checked>
        else ()
};

declare %private function local:traverse($path as xs:string) as element()* {
    for $coll in xmldb:get-child-collections($path)
    return 
        if ($coll='modules' or $coll='api') 
        then local:check-xqueries(concat($path, '/', $coll)) 
        else local:traverse(concat($path, '/', $coll))
};

(: default of 'empty' does all :)
let $packages       := if (request:exists()) then (request:get-parameter('pkg','')) else (('ada', 'art', 'decor/services', 'fhir', 'terminology', 'tools/oids'))

let $result         := 
    if (sm:is-dba(get:strCurrentUserName())) then (
        let $results    := 
            for $pkg in $packages
            (: do some input cleansing. no ../ constructs :)
            let $path   := string-join(('xmldb:exist:///db/apps',replace($pkg, '^\.+/*','')),'/')
            return
                if (xmldb:collection-available($path)) then local:traverse($path) else ()
        
        return
        <result failed="{count($results//info[@result='fail'])}" passed="{count($results//info[@result='pass'])}">
        {
            for $res in $results
            (: this puts fail before pass, but without second "order by" things would go random within first group :)
            order by $res/*/@result, $res/lower-case(@xquery)
            return
                $res
        }
        </result>
    ) 
    else (
        <result>NO PERMISSION</result>
    )

return 
    $result