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 xmldb       = "http://exist-db.org/xquery/xmldb";
import module namespace sm          = "http://exist-db.org/xquery/securitymanager";
import module namespace repo        = "http://exist-db.org/xquery/repo";
import module namespace aduser      = "http://art-decor.org/ns/art-decor-users" at "api/api-user-settings.xqm";
import module namespace adserver    = "http://art-decor.org/ns/art-decor-server" at "api/api-server-settings.xqm";
import module namespace adpfix      = "http://art-decor.org/ns/art-decor-permissions" at "api/api-permissions.xqm";
import module namespace art         = "http://art-decor.org/ns/art" at "modules/art-decor.xqm";
import module namespace gg          = "http://art-decor.org/ns/decor/governancegroups" at "api/api-decor-governancegroups.xqm";

(: The following external variables are set by the repo:deploy function :)

(:  home="/Applications/eXist-db" 
    dir="/Applications/eXist-db/webapp/WEB-INF/data/expathrepo/ART-1.1.37/." 
    target="/db/apps/art" 
    root="/db/apps/"
:)

(: file path pointing to the exist installation directory :)
declare variable $home external;
(: path to the directory containing the unpacked .xar package :)
declare variable $dir external;
(: the target collection into which the app is deployed :)
declare variable $target external;
(:install path for art (/db, /db/apps), no trailing slash :)
declare variable $root := repo:get-root();

declare %private function local:copy($source as xs:string, $target as xs:string, $base as xs:boolean) {
let $dirName       := tokenize($source,'/')[last()]
let $targetDirName := if ($base) then $target else (concat($target,'/',$dirName))
let $createDir     := 
    if (not(xmldb:collection-available($targetDirName))) then
        xmldb:create-collection(string-join(tokenize($targetDirName,'/')[not(position()=last())],'/'),tokenize($targetDirName,'/')[last()])
    else ()
let $chmodDir       :=
    if (tokenize($targetDirName,'/')[last()] = 'user-info') then (
        sm:chmod(xs:anyURI($targetDirName), 'rwsrwsr-x'), sm:chown(xs:anyURI($targetDirName), 'admin:dba')
    ) else ()
let $copyResources :=
    for $r in xmldb:get-child-resources($source)
    return
        if (not($r=xmldb:get-child-resources($targetDirName))) then
            xmldb:copy-resource($source, $r, $targetDirName, $r)
        else ()
let $copyCollections :=
    for $c in xmldb:get-child-collections($source)
    return
        local:copy(concat($source,'/',$c),$targetDirName, false())

return ()
};

declare %private function local:copyArtUI() {
let $sourcecoll := concat($root,'/art/resources')
let $targetcoll := concat($root,'/art-data/resources')
let $result     :=
    if (doc-available(concat($targetcoll,'/local-header-resources.xml'))) then () else (
        xmldb:copy-resource($sourcecoll, 'local-header-resources.xml', $targetcoll, 'local-header-resources.xml')
    )
let $result     :=
    for $xml in collection($sourcecoll)/menu[section]
    let $resname    := util:document-name($xml)
    return (
        xmldb:store($targetcoll, $resname, $xml),
        art:updateArtMenu($resname)
    )
    
return ()
};

declare %private function local:upgradeArtUISettings() {
(:cannot call getServerXSL as that would hide what the real setting is if it were one the ones below here:)
let $server-xsl := adserver:getServerSettings()/xformStylesheet
let $upgrade    :=
    switch ($server-xsl)
    case 'apply-rules-artdecororg.xsl' return (
        adserver:setServerLogoAndUrl('art-decor-logo40.png','https://art-decor.org'),
        adserver:setServerMenuTemplate('artdecororg-menu-template.xml'),
        adserver:setServerXSLArt('apply-rules.xsl')
    )
    case 'apply-rules-nictiznl.xsl' return (
        adserver:setServerLogoAndUrl('nictiz-logo.png','https://www.nictiz.nl'),
        adserver:setServerMenuTemplate('art-menu-template.xml'),
        adserver:setServerXSLArt('apply-rules.xsl')
    )
    case 'apply-rules-terminology-nictiznl.xsl' return (
        adserver:setServerLogoAndUrl('nictiz-logo.png','https://www.nictiz.nl'),
        adserver:setServerMenuTemplate('terminology-menu-template.xml'),
        adserver:setServerXSLArt('apply-rules.xsl')
    )
    case 'apply-rules-terminology.xsl' return (
        adserver:setServerLogoAndUrl('nictiz-logo.png','https://www.nictiz.nl'),
        adserver:setServerMenuTemplate('terminology-menu-template.xml'),
        adserver:setServerXSLArt('apply-rules.xsl')
    )
    case 'apply-rules-xis.xsl' return (
        adserver:setServerLogoAndUrl('nictiz-logo.png','https://www.nictiz.nl'),
        adserver:setServerMenuTemplate('xis-menu-template.xml'),
        adserver:setServerXSLArt('apply-rules.xsl')
    )
    default return ()

return ()
};

(: check if message collection exists, if not then create and set permissions :)
let $installextras          := local:copy(concat($target,'/install-data'),concat($root,'art-data'), true())
let $fixpermissions         := adpfix:setArtPermissions()
(:let $fixpermissions         := adpfix:setDecorPermissions():)
let $mergesettings          := adserver:mergeServerSettings()
(:  if this is the first install, then the art menu may not exist yet which triggers an error in updating, but 
    even if it would exist it would be redudant to do as copyArtUI() will handle updating the menu file
    Switching the order of art:saveFormResources and copyArtUI would not help as copyArtUI needs up2date 
    ART form-resources to operate :)
let $doArtMenuUpdate        := false()
let $updateformresources    := art:saveFormResources('art',art:mergeLocalLanguageUpdates('art'), $doArtMenuUpdate)
let $updateui               := local:copyArtUI()
let $upgradeuisettings      := local:upgradeArtUISettings()
let $installggartdecor      := gg:updateGroups(<group id="2.16.840.1.113883.3.1937" defaultLanguage="en-US">
        <name language="en-US">ART-DECOR</name>
        <name language="de-DE">ART-DECOR</name>
        <name language="nl-NL">ART-DECOR</name>
        <desc language="en-US"/>
        <desc language="de-DE"/>
        <desc language="nl-NL"/>
        <copyright years="2009-{format-date(current-date(),'[Y0001]')}">
            <addrLine type="uri">http://www.art-decor.org</addrLine>
        </copyright>
    </group>)
(: 2017-03-25 patch required because of incorrectly added user info data :)
(:let $patchuserdata          := aduser:patchAllProjectPreferences():)
(: 2017-06-12 patch required because groups with spaces in the name would be concatenated in a way that you could not untangle them :)
(:let $patchuserdata          := aduser:patchAllUserGroups():)

(: explicitly set the Orbeon version on servers that did not have the setting yet. This facilitates the ability to configure it in the art-settings :)
let $updatexforms           := adserver:setServerOrbeonVersion(adserver:getServerOrbeonVersion())
(: upgrade or downgrade the XForms depending on Orbeon version :)
let $updatexforms           := if (adserver:getServerOrbeonVersion() = '3.9') then adpfix:updateXForms('downgrade') else adpfix:updateXForms('upgrade')
return ()