plugins {
    id 'idea'
    id 'eclipse'
    id 'com.github.johnrengelman.shadow' version '7.1.2'
    id 'com.github.jk1.dependency-license-report' version '2.0' // 2.1 requires Java 11
    id "com.github.ben-manes.versions" version "0.46.0"
    id 'distribution'
}

// NOTE: version is specified in gradle.properties
// NOTE: All dependencies should be specified in platform/build.gradle

defaultTasks ':distZip'

// A resolvable configuration to collect test reports data from subprojects
configurations {
    testReportData {
        canBeResolved = true
        canBeConsumed = false
        attributes {
            attribute(Category.CATEGORY_ATTRIBUTE, objects.named(Category, Category.DOCUMENTATION))
            attribute(DocsType.DOCS_TYPE_ATTRIBUTE, objects.named(DocsType, 'test-report-data'))
        }
    }
}

project.ext {
    // to exclude storage plugins, set project property storage.excludes with a list of storage plugin short-names separated by comma
    // e.g. -Pstorage.excludes="nfs,azure"
    storageIncludes = []
    // exclude nfs storage-plugin by default due to CVEs introduced by transient dependency (Netty 3.10.6.Final) from com.emc.ecs:nfs-client
    storageExcludes = ['nfs']

    if (project.hasProperty('storage.excludes')) {
        storageExcludes = []
        storageExcludes.addAll(project.property('storage.excludes').split(','))
    }
    file("${rootProject.projectDir}/storage-plugins").eachDir {
        if (storageExcludes.contains(it.name.split('-storage')[0])) {
            logger.warn("storage-plugin project ${it.name} is excluded.")
        } else {
            storageIncludes.add(it.name.split('-model')[0])
            logger.info("Added storage-plugin project ${it.name}.")
        }
    }
    storageIncludes.unique()

    // to exclude filter plugins, set project property filter.excludes with a list of plugin names separated by comma
    // e.g. -Pfilter.excludes="cas-extractors,fs-filters"
    filterIncludes = []
    filterExcludes = []
    if (project.hasProperty('filter.excludes')) {
        filterExcludes.addAll(project.property('filter.excludes').split(','))
    }
    file("${rootProject.projectDir}/filter-plugins").eachDir {
        if (filterExcludes.contains(it.name.split('-model')[0])) {
            logger.warn("filter-plugin project ${it.name} is excluded.")
        } else {
            filterIncludes.add(it.name.split('-model')[0])
            logger.info("Added filter-plugin project ${it.name}.")
        }
    }
    filterIncludes.unique()
}

// depend on testReportData from all subprojects
dependencies {
    testReportData project(':ecs-sync-cli')
    testReportData project(':ecs-sync-core')
    testReportData project(':ecs-sync-ctl')
    testReportData project(':ecs-sync-model')
    file('storage-plugins').eachDir {
        testReportData project(":storage-plugins:${it.name}")
    }
    file('filter-plugins').eachDir {
        testReportData project(":filter-plugins:${it.name}")
    }
}

// use the "testReport" task to generate an aggregated JUnit report
tasks.register('testReport', TestReport) {
    destinationDir = file("$buildDir/reports/allTests")
    // Use test results from testReportData configuration
    testResultDirs.from(configurations.testReportData)
}

import com.github.jk1.license.render.*

licenseReport {
    renderers = [new InventoryHtmlReportRenderer(), new CsvReportRenderer()]
}
generateLicenseReport.dependsOn subprojects.collect { it.tasks.withType(JavaCompile) }

distributions {
    main {
        contents {
            from 'readme.txt'
            from 'license.txt'
            from 'license'
            into('3rd-party-licenses') {
                from generateLicenseReport
            }
            from { project(':ecs-sync-cli').shadowJar }
            from { customPluginListFile }
            from { project(':ecs-sync-ctl').shadowJar }
            from 'script'
            into('samples') {
                from 'sample'
            }
            /*
            into('docker') {
                from 'docker'
            }
            */
        }
    }
}

def isNonStable = { String version ->
    def stableKeyword = ['RELEASE', 'FINAL', 'GA'].any { it -> version.toUpperCase().contains(it) }
    def regex = /^[0-9,.v-]+(-r)?$/
    return !stableKeyword && !(version ==~ regex)
}

dependencyUpdates {
    revision = 'release'
    checkForGradleUpdate = true
    gradleReleaseChannel = 'current'
    checkConstraints = true
    checkBuildEnvironmentConstraints = true
    rejectVersionIf {
        isNonStable(it.candidate.version) || it.candidate.version == '20040117.000000' // bogus commons-cli version
    }
}

task customPluginListFile {
    def outputFile = new File(buildDir, "custom-plugin-package.txt")
    if (outputFile.exists()) outputFile.delete()
    outputs.file(outputFile)

    doLast {
        if (!project.ext.storageExcludes.isEmpty() || !project.ext.filterExcludes.isEmpty()) {
            outputFile.write("Storage-Plugin-Includes: " + project.ext.storageIncludes.toString().replace("[", "").replace("]", "").replace("-storage", "") + "\n")
            outputFile.append("Storage-Plugin-Excludes: " + project.ext.storageExcludes.toString().replace("[", "").replace("]", "") + "\n")
            outputFile.append("Filter-Plugin-Includes: " + project.ext.filterIncludes.toString().replace("[", "").replace("]", "") + "\n")
            outputFile.append("Filter-Plugin-Excludes: " + project.ext.filterExcludes.toString().replace("[", "").replace("]", "") + "\n")
        }
    }
}
