subprojects {
    ext {
        pluginDictionaryDir = file("${lightPluginDir}/dictionary")
    }

    configurations {
        provided_zip_data
        provided_data
        zip_data
        data
    }

    dependencies {
    	//FIXME: replace all log4j to slf4j logger
        compileOnly "org.apache.logging.log4j:log4j-slf4j-impl:${version_log4j2}"

    	testCompile "org.apache.logging.log4j:log4j-slf4j-impl:${version_log4j2}"
    }

    writeBuildInfo.dependsOn.add('assemble')
    build.dependsOn.add('writeBuildInfo')
    jar.dependsOn('writeFile')

    afterEvaluate { Project project ->

        writeFile {
            if (project.hasProperty('plugin_alias')) {
                line("plugin_alias: ${project.plugin_alias}")
                line("name: ${project.name}")
            }

            outputDir = genPluginDir
        }

        task pluginDictionaryWriteVersion(type: com.exactpro.sf.WriteFileTask) {
            if (project.hasProperty('plugin_alias')) {
                line('lightweight: true')
                line("plugin_alias: ${project.plugin_alias}_dictionary")
                line("name: ${project.name}_dictionary")
            }

            outputDir = pluginDictionaryDir
        }

        configure([writeFile, pluginDictionaryWriteVersion]) {
            onlyIf {
                project.hasProperty('plugin_alias')
            }

            if (project.hasProperty('plugin_alias')) {
                line ("build_number: ${build_number}")
                line ("revision: ${revision}")
                line ("git_hash: ${git_hash}")
                line ('group: sailfish')
                line ("branch: ${project.branch}")
                line ("version: ${sailfish_version_major}.${sailfish_version_minor}.${revision}.${build_number}")
            }
            fileName    = 'VERSION'
        }

        checkCompatibility {
            versionFile = writeFile.outputFile
        }
        
        def publishPluginData = fileTree(mainPluginDir) +
                                fileTree(genPluginDir) +
                                fileTree(externalPluginDir) +
                                fileTree(mainWorkspaceDir) +
                                fileTree(genWorkspaceDir) +
                                fileTree(externalWorkspaceDir)

        task publishPlugin(type: Copy) { }

        task zipRelease (type: Zip) {
            if (project.hasProperty('plugin_name')) {
                archiveName = getReleaseName(project.plugin_name)
                destinationDir = getReleaseDir(project.buildDir, project.plugin_name)
            }

            if (project.hasProperty('link_last_build')) {
                doLast {
                    createLink(destinationDir, archiveName, 'last_build')
                }
            }
        }

        task publishPluginDictionary(type: Copy) { }

        task zipReleasePluginDictionary (type: Zip) {
            if (project.hasProperty('plugin_name')) {
                def name = "${project.plugin_name}_dictionary"
                archiveName = getReleaseName(name)
                destinationDir = getReleaseDir(project.buildDir, name)
            }

            doLast {
                createLink(destinationDir, archiveName, 'last_build_dictionary')
            }
        }


        configure([publishPlugin, zipRelease,
                   publishPluginDictionary, zipReleasePluginDictionary]) {

            onlyIf {
                project.hasProperty('plugin_alias')
            }

            dependsOn.add('checkCompatibility')
            dependsOn.add('copyFromData')
            dependsOn.add('copyFromProvidedData')
        }

        configure([publishPlugin, zipRelease]) {
            dependsOn.add('jar')
            dependsOn.add('writeFile')
            dependsOn.add('generateSailfishHelp')

            if (project.hasProperty('plugin_name')) {
                def pluginFolderName = getZipPluginFolder(project.plugin_name)

                into(pluginFolderName) {
                    from publishPluginData
                }

                into("${pluginFolderName}/${zipPluginLibsDir}") {
                    from configurations.compile - configurations.compileOnly
                    from(libsDir) {
                        exclude '*-sources.jar'
                        exclude '*-tests.jar'
                    }
                }
            }
        }

        configure([publishPluginDictionary, zipReleasePluginDictionary]) {
            dependsOn.add('pluginDictionaryWriteVersion')

            if (project.hasProperty('plugin_name')) {
                def pluginFolderName = getZipPluginFolder("${project.plugin_name}_dictionary")

                into (pluginFolderName) {
                    from fileTree(pluginDictionaryDir) + publishPluginData.matching {
                        include 'cfg/dictionaries.xml'
                        include 'cfg/dictionaries/*.xml'
                        include 'cfg/data.xml'
                        include 'cfg/data/*.xml'
                    }
                }
            }
        }

        configure([publishPlugin, publishPluginDictionary]) {
            into sharedWorkspaceDir
        }

        configure([zipRelease, zipReleasePluginDictionary]) {
            includeEmptyDirs = false
            zip64 = true
            duplicatesStrategy = 'EXCLUDE'
        }
    }

    task copyFromData (type: Copy) {
        into externalWorkspaceDir

        from {
            configurations.zip_data.collect { zipTree(it) }
        }
        from {
            configurations.data
        }
    }

    task copyFromProvidedData (type: Copy) {
        into providedWorkspaceDir

        from {
           configurations.provided_zip_data.collect { zipTree(it) }
        }
        from { 
            configurations.provided_data
        }
    }
	test.dependsOn.add('copyFromProvidedData')

    task cleanSharedWorkspace (type: Delete) {
        doLast {
            fileTree(dir: sharedWorkspaceDir).visit { element ->
                delete element.file
            }
        }
    }

    task generateSailfishHelp(type: JavaExec) {
        dependsOn.add("checkCompatibility")
        afterEvaluate { Project project ->
            onlyIf {
                project.hasProperty('plugin_name') && project.hasProperty('plugin_alias')
            }
            if (project.hasProperty('plugin_name') && project.hasProperty('plugin_alias')) {
                classpath sourceSets.main.compileClasspath
                args project.plugin_alias, project.plugin_name, mainPluginDir, externalPluginDir, mainWorkspaceDir, genWorkspaceDir, externalWorkspaceDir, genPluginDir
                main "com.exactpro.sf.help.HelpBuilder"
            }
        }
    }
}

def getZipPluginFolder(plugin_name) {
    return "${zipPluginDir}/${plugin_name}"
}

def getReleaseName(plugin_name) {
    return "${plugin_name}_${sailfishVersion}.${revision}_b${build_number}_core_${sailfishVersion}.${min_core_revision}.zip"
}

def getReleaseDir(buildDir, plugin_name) {
    return file("${buildDir}/release/${plugin_name}")
}

def createLink(releaseDir, releaseName, linkName) {
    exec {
        def link = file("${releaseDir}/${linkName}.zip")
        if (!link.exists()) {
            commandLine 'ln', '-s', releaseName, link
        } else {
            commandLine 'echo', 'link is already created'
        }
    }
}

// Setting this property to true will make the publish tasks
// skip this module (in our case, the root module):
tasks.withType(PublishToMavenRepository).all { publishTask ->
    publishTask.enabled = false
}