xquery version "1.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";
import module namespace aduser = "http://art-decor.org/ns/art-decor-users" at "../api/api-user-settings.xqm";

declare namespace sm  = "http://exist-db.org/xquery/securitymanager";
declare namespace xis = "http://art-decor.org/ns/xis";

let $accounts           := doc($get:strTestAccounts)/xis:testAccounts
(: create collections and groups if needed :)
let $groups :=
    for $account in $accounts/xis:testAccount[string-length(@name) gt 0]
    let $accountName    := $account/@name/string()
    let $accountMembers := if (sm:group-exists($accountName)) then sm:get-group-members($accountName) else ()
    let $memberList     :=
        <members xmlns="http://art-decor.org/ns/xis">
        {
            for $member in $accountMembers
            let $memberName := aduser:getUserDisplayName($member)
            order by $member
            return
                <user id="{$member}">{if (empty($memberName)) then $member else ($memberName)}</user>
        }
        </members>
    return
        if (sm:group-exists($accountName)) then 
            update replace $account/xis:members with $memberList
        else ()
        
return
    <data-safe>true</data-safe>
