import java.util.zip.ZipFile

// fix versions for #1200
buildscript {
    configurations {
        jbake {
            exclude group: 'org.eclipse.jetty'
        }
    }
    configurations.all {
        resolutionStrategy.eachDependency { DependencyResolveDetails details ->
            if (details.requested.group == 'org.ysb33r.gradle' && details.requested.name == 'grolifant' && details.requested.version == '0.12.1') {
                details.useVersion '0.16.1'
                details.because 'jcenter redirect'
                System.out.println ">>>>>>>>> fix grolifant"
            }
        }
    }
    dependencies {
        classpath libs.html.sanity.check
    }
}
// /fix versions for #1200

/*
 * This build file is part of the docToolchain
 */

plugins {
    alias(libs.plugins.htmlSanityCheck)
    alias(libs.plugins.versions)
    alias(libs.plugins.openapi.generator)
    alias(libs.plugins.undercouch.download)
    alias(libs.plugins.jbake.site)
}

apply plugin:'groovy'

dependencies {
    repositories {
        maven {
            credentials {
                username mavenUsername
                password mavenPassword
            }
            url mavenRepository
        }
    }

    testImplementation(libs.spock.reports) {
        exclude group: 'org.codehaus.groovy', module: 'groovy-xml'
    }
    testImplementation(
            (libs.junit),
            (libs.spock.core),
            gradleTestKit(),
            (libs.jsoup),
    )
    if (file("libs/org/docToolchain/core-${project.properties.dtc_version}.jar").exists()) {
        testImplementation(files("libs/org/docToolchain/core-${project.properties.dtc_version}.jar"))
    } else {
        testImplementation("org.docToolchain:core")
    }
    testRuntimeOnly(libs.byte.buddy)
    compileClasspath((libs.http.client))
}
test {
    useJUnitPlatform()
}

if (project.name!=rootProject.name) {
    // disable all tasks which are not docToolchain tasks
    // this avoids for example that task 'check' runs if invoked in main project
    gradle.taskGraph.whenReady {
        tasks.each { task ->
            if (task.group in ['docToolchain', 'Documentation', 'docToolchain helper']
                    || task.name in ['htmlSanityCheck', 'streamingExecute', 'tasks', 'clean']) {
                task.enabled = true
            } else {
                task.enabled = false
            }
        }
    }
    if (docDir=='.') {
        throw new Exception("""
You are running docToolchain as git submodule.
That is great!
Currently, it is still configured to build its own manual,
because the property docDir points to docToolchain itself.
Please configure docToolchain to point to your doc-sources.
You can do so by specifying it in your build.gradle or on the
command line. Example:
./gradlew generateHTML -PdocDir=../.
see https://docs-as-co.de/getstarted/tutorial2 for more details.
        """)
    }
}

//all available docToolchain modules
//the first is mandatory
apply from: 'scripts/AsciiDocBasics.gradle'
//the following are optional
apply from: 'scripts/fixEncoding.gradle'
apply from: 'scripts/prependFilename.gradle'
apply from: 'scripts/exportEA.gradle'
apply from: 'scripts/exportPPT.gradle'
apply from: 'scripts/exportVisio.gradle'
apply from: 'scripts/exportChangelog.gradle'
apply from: 'scripts/exportContributors.gradle'
apply from: 'scripts/exportJiraIssues.gradle'
apply from: 'scripts/exportJiraSprintChangelog.gradle'
apply from: 'scripts/exportExcel.gradle'
apply from: 'scripts/exportMarkdown.gradle'
apply from: 'scripts/pandoc.gradle'
apply from: 'scripts/publishToConfluence.gradle'
apply from: 'scripts/htmlSanityCheck.gradle'
apply from: 'scripts/collectIncludes.gradle'
apply from: 'scripts/exportMetrics.gradle'
apply from: 'scripts/exportOpenApi.gradle'
apply from: 'scripts/downloadTemplate.gradle'
apply from: 'scripts/generateSite.gradle'
apply from: 'scripts/copyThemes.gradle'
apply from: 'scripts/fixGlobalReferences.gradle'
apply from: 'scripts/customTasks.gradle'
apply from: 'scripts/exportConfluence.gradle'
apply from: 'scripts/exportStructurizr.gradle'
apply from: 'scripts/generateContent.gradle'

task autobuildSite(
    group: 'docToolchain',
    description: 'linux: automatically re-build the static site every time a change in src/docs is detected') {
    // this is a stub ony to show some help for the "tasks" task
    // the real implementation can be found in /bin/doctoolchain

}
task prepareDist() {
    if (!file("libs/org/docToolchain/core-${project.properties.dtc_version}.jar").exists()) {
        dependsOn gradle.includedBuild('core').task(':release-core')
    }
    doLast {
        def distFolder = "dist/docToolchain-"+dtc_version
        println "generate distribution for "+dtc_version
        new File(buildDir, distFolder).mkdirs()
        copy{
            from new File("./bin")
            into new File(buildDir, distFolder+"/bin")
        }
        copy{
            from (new File("./gradle")) {
                include "*"
                include "**/*"
            }
            into new File(buildDir,distFolder+"/gradle")
        }
        copy{
            from (new File("./resources")) {
                include "*"
                include "**/*"
            }
            into new File(buildDir,distFolder+"/resources")
        }
        copy{
            from (new File("./libs")) {
                include "*"
                include "**/*"
            }
            into new File(buildDir,distFolder+"/libs")
        }
        copy{
            from (new File("./core")) {
                include "*"
                include "**/*"
            }
            into new File(buildDir,distFolder+"/core")
        }
        copy{
            from new File("./scripts")
            into new File(buildDir,distFolder+"/scripts")
        }
        copy{
            from (new File("./src/site")) {
                include "*"
                include "**/*"
            }
            into new File(buildDir,distFolder+"/src/site")
        }
        copy{
            from (new File("./template_config")) {
                include "*"
                include "**/*"
            }
            into new File(buildDir,distFolder+"/template_config")
        }
        copy{
            from (new File(".")) {
                include '.gitmodules'
                include 'build.gradle'
                include 'gradle.properties'
                include 'gradlew*'
                include 'init.gradle'
                include 'LICENCE'
                include 'README.adoc'
                include 'settings.gradle'
                include 'libs.versions.toml'
            }
            into new File(buildDir,distFolder+"/.")
        }
    }
}
task createDist(type: Zip, dependsOn: prepareDist) {
    def distFolder = "dist"
    from new File(buildDir,distFolder)
    include '*'
    include '**/*' //to include contents of a folder present inside Reports directory
    archiveFileName = 'docToolchain-'+dtc_version+'.zip'
    destinationDirectory = buildDir
}

task downloadDependencies {
    doLast {

        project.repositories {
            ruby {
                gems()
            }
        }

        [configurations, buildscript.configurations].each { config ->
            config.findAll{ it.canBeResolved && !it.name?.startsWith("test")}.each {
                println "-> " + it.name
                it.resolve()
            }
        }
    }
}

// let's set a defaultTask for convenience
//defaultTasks 'exportChangeLog','exportJiraIssues','asciidoctor'
//defaultTasks 'generateHTML', 'htmlSanityCheck'
//defaultTasks 'exportMarkdown', 'exportContributors', 'generateHTML', 'htmlSanityCheck'
//copyDocs
