xquery version "3.1";

(:~
 : This script removes existing (sample) data from the data collection and triggers a
 : publish process for the main edition of the Ahiqar project with tg-connect.
 : Can also publish any sub-collection or resource by adjusting $uri at local:publish().
 :)

import module namespace connect="https://sade.textgrid.de/ns/connect" at "/db/apps/textgrid-connect/modules/connect.xqm";
import module namespace commons="http://ahiqar.uni-goettingen.de/ns/commons" at "modules/commons.xqm";

(:~
 : Remove all data present. Mainly used to cleanup sample data.
 : To not interfere with the collection trigger we are going to remove all
 : resources and not the collections themself.
 :)
declare function local:cleanup() {
    for $collection in ($commons:data, $commons:agg, $commons:meta, $commons:tile, $commons:json, $commons:html, $commons:tmp)
    where xmldb:collection-available($collection)
    let $resources := xmldb:get-child-resources($collection)
    for $resource in $resources
    return
        xmldb:remove($collection, $resource)
};

declare function local:publish($uri as xs:string, $recursive as xs:boolean) {
    let $sid := commons:get-textgrid-session-id()
    let $user := "admin"
    let $password := commons:get-secret("EXIST_ADMIN_PW") || "" (: cast empty sequence as empty string :)
    return
        connect:publish($uri, $sid, $user, $password, false(), $recursive)
};

declare function local:log($message as xs:string) {
    util:log-system-out( util:system-time() || " ::: " || $message )
};

(: useful URIs of Aggregations:
 : main         textgrid:3r132
 : syriac       textgrid:3r84g
 : karshuni     textgrid:3r84h
 : arabic       textgrid:3r9ps
 : neo-aramaic  textgrid:40xnp
 : sogdian      textgrid:41np5
 :   :)
let $uris := request:get-parameter("uri", "textgrid:3r132, textgrid:3r84g, textgrid:3r84h, textgrid:3r9ps, textgrid:40xnp, textgrid:41np5")
let $uris := request:get-parameter("uri", "textgrid:3r678")
let $recursive := request:get-parameter("recursive", "true") => xs:boolean()
let $cleanup := request:get-parameter("cleanup", "false") => xs:boolean()
return
(   
    local:log("STARTING IMPORT"),
    for $uri at $pos in tokenize($uris, ", ")
    let $cleanup := if(xs:boolean($cleanup) and ($pos eq 1)) then local:cleanup() else ()
    let $log := local:log("publishing " || $uri)
    return
        local:publish($uri, $recursive),

    local:log("FINISHED IMPORT")
)