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 namespace sm                = "http://exist-db.org/xquery/securitymanager";

let $user       := if (request:exists()) then request:get-parameter('username',()) else ()
let $groups     := if (string-length($user) = 0) then sm:list-groups() else (sm:get-user-groups($user))

let $user       := 
    if (get:strCurrentUserName() = ('guest','')) then 'guest' else 
    if (string-length($user) gt 0) then $user else (get:strCurrentUserName())

return
<groups user="{$user}">
{
    for $group at $i in $groups
    let $userExists := try { sm:user-exists($group) } catch * {false()}
    order by lower-case($group)
    return
        <group navkey="{$i}">
        {
            if ($userExists) then attribute userGroup {'true'} else (),
            $group
        }
        </group>
}
</groups>
