import java.util.zip.ZipFile
import java.util.zip.ZipEntry
import java.util.regex.Matcher
buildscript {
  repositories {
        mavenCentral()
        maven {
          url "https://plugins.gradle.org/m2/"
        }
  }
  dependencies {
        classpath "gradle.plugin.org.jenkins-ci.tools:gradle-jpi-plugin:0.28.0"
        classpath 'org.yaml:snakeyaml:1.17'
  }
}
apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: 'org.jenkins-ci.jpi'

def pluginsPath = System.getenv('PLUGIN_OUTPUT_DIR') ?: 'plugins'
def installedPluginFile = System.getenv('PLUGIN_OUTPUT_FILE') ?: 'installed_plugins'

repositories {
    mavenCentral()
}

dependencies {
    jenkinsPlugins(parsePluginList())
}

// resolve all of the dependencies for the plugin files sepcified in
// jenkinsPlugins
task plugins(type: Copy, dependsOn: [clean]){
    from configurations.jenkinsPlugins
    include '**/*.hpi'
    include '**/*.jpi'
    into "${pluginsPath}"

    // Strip the version from the plugin name
    def mapping = [:]
    doFirst {
        configurations.jenkinsPlugins.resolvedConfiguration.resolvedArtifacts.each {
            mapping[it.file.name] = "${it.name}.jpi"
        }
    }
    rename { mapping[it] }

    // Jenkins 1.x comes with 'bundled' plugins, that will be resintalled and
    // override manually installed plugin versions, unless there is an empty
    // 'pinned' jpi file. Create a pinned file for each plugin to avoid any override
    // issues.
    // NOTE: this is no longer the case with Jenkins 2.x
    doLast {
        File pluginPath = new File("${pluginsPath}")
        pluginPath.eachFile { plugin ->
            if ( plugin.isFile() ) {
                new File("${plugin}.pinned").createNewFile()
            }
        }
        showDownloadedPlugins()
    }
}

def parsePluginList() {
    String pluginConfig = System.getenv('PLUGIN_CONFIG') ?: 'test_data/plugins.yml'
    String pluginConfigKey = System.getenv('PLUGIN_CONFIG_KEY') ?: null
    org.yaml.snakeyaml.Yaml yaml = new org.yaml.snakeyaml.Yaml()
    def pluginList = []
    if (pluginConfigKey == null) {
        pluginList = yaml.load(new File(pluginConfig).text)
    } else {
        def map = yaml.load(new File(pluginConfig).text)
        pluginList = map[pluginConfigKey]
    }
    return pluginList
}


task show {
    doLast {
        showDownloadedPlugins()
    }
}

// Display the final versions of all plugins after dependency resolution
// Additionally write this information to a file.
void showDownloadedPlugins() {
    String pluginsPath = System.getenv('PLUGIN_OUTPUT_DIR') ?: 'plugins'
    String installedPluginFile = System.getenv('PLUGIN_OUTPUT_FILE') ?: 'installed_plugins'
    println("The following plugins were downloaded to ${pluginsPath}")
    File pluginPath = new File("${pluginsPath}")
    File showFile = new File("${installedPluginFile}")
    pluginPath.listFiles().findAll { it.name =~ '.*jpi$' }.sort { it.name }.each() { plugin ->
        ZipFile jpiContents = new ZipFile(plugin)
        ZipEntry manifestFile = jpiContents.entries().find { it.getName() == "META-INF/MANIFEST.MF" }
        Matcher matcher = jpiContents.getInputStream(manifestFile).text =~ 'Plugin-Version: ([\\.\\d]+)'
        String pluginName = plugin.name.split('\\.')[0]
        String version = matcher[0][1]
        String pluginNameAndVersion = "${pluginName}: ${version}"
        println(pluginNameAndVersion)
        showFile.append("${pluginNameAndVersion}\n")
    }
    println("This data was also written to ${installedPluginFile}")
}

clean {
    delete "${pluginsPath}"
    delete "${installedPluginFile}"
}
