dependencies {
    implementation "commons-cli:commons-cli:1.2"
    implementation 'org.apache.felix:org.apache.felix.framework:5.4.0'
    // compile( "org.osgi:org.osgi.core:4.3.1" )
}

def archiveJarName="${project.name}-${project.version}.jar"
def jposCopySpec = copySpec {
    def cfg = new Properties()
    def target = project.hasProperty('target') ? target : 'devel'
    cfg.put('jarname', archiveJarName.toString())
    cfg.put('target', target.toString())
    File cfgFile = file("${target}.properties")
    if (cfgFile.exists()) {
        cfgFile.withInputStream{
            cfg.load(it);   
        }
    }
    from(file("src/dist")) {
        exclude 'cfg/*.jks'
        filter(
            org.apache.tools.ant.filters.ReplaceTokens, 
            tokens: cfg
        )
    }
    from(file("src/dist")) {
        include 'cfg/*.jks'
    }
    from(jar) {
        rename archiveJarName, "${cfg.jarname}"
    }
    into("lib") {
        from(configurations.runtimeClasspath)
    }
}

task listJars {
    doLast {
        configurations.testCompile.each { File file -> println file.name }
    }
}
 
jar () {
    manifest {
        def manifestClasspath = configurations.runtimeClasspath.collect { "lib/" + it.getName() }.join(' ') 
        attributes 'Implementation-Title': 'jPOS', 
                   'Implementation-Version': project.version,
                   'Main-Class': 'org.jpos.qnode.QNode',
                   'Class-Path': manifestClasspath
    }
}

task sourceJar( type: Jar ) {
    classifier = "sources"
    from sourceSets.main.allSource
}

task javadocJar (type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from new File(project.buildDir, 'docs/javadoc')
}

artifacts {
    archives sourceJar, javadocJar
}

task dist (type: Tar) { 
    dependsOn 'assemble', 'sourceJar'
    compression = Compression.GZIP
    includeEmptyDirs true
    with jposCopySpec
    into "jpos-$project.version"
}

task version (type: JavaExec, dependsOn: classes) {
    description = "Display jPOS Version"
    main = 'org.jpos.qnode.QNode'
    args = "--version".split().toList()
    classpath sourceSets.main.runtimeClasspath, configurations.runtime
}

class GitRevisionTask extends DefaultTask
{
    @InputFile @Optional
    File gitHead
    boolean gotHead

    File getRefFile()
    {
        return new File(gitHead.parent,gitHead.text.replace('ref: ', '').trim())
    }

    @OutputFile
    File outputFile

    @TaskAction
    public void writeFile()
    {
        Properties props=new Properties()
        if (gotHead) {
            File ref=getRefFile()
            if (ref.exists()) {
                props.put("branch",ref.getName())
                props.put("revision",ref.text.substring(0,7))
            } else {
                props.put("branch", "detached");
                props.put("revision", gitHead.text.substring(0,7))
            }
        } else {
            props.put("branch", "unknown");
            props.put("revision", "unknown");
        }
        props.store(new FileOutputStream(outputFile),"Revision Properties")
    }
}

class BuildTimestampTask extends DefaultTask {
    // We don't want to declare @OutputFile, we need a fresh timestamp on every run
    File outputFile

    @TaskAction
    public void writeFile() {
        new File(outputFile.parent).mkdirs()
        Properties props=new Properties()
        props.put("version", project.version);
        props.put("buildTimestamp", new Date().format("yyyy-MM-dd HH:mm:ss z"));
        props.store(new FileOutputStream(outputFile),"Revision Properties")
    }
}

task createRevisionPropertyFile(type: GitRevisionTask) {
    gitHead = "$rootDir/.git/HEAD" as File
    gotHead = gitHead.exists()
    if (!gotHead)
        gitHead = null;
    outputFile = "$sourceSets.main.output.resourcesDir/org/jpos/qnode/revision.properties" as File
}

task createBuildTimestampPropertyFile(type: BuildTimestampTask) {
    outputFile = "$sourceSets.main.output.resourcesDir/org/jpos/qnode/buildinfo.properties" as File
}

processResources.dependsOn createBuildTimestampPropertyFile, createRevisionPropertyFile

task installApp(type: Sync) {
    description 'Installs jPOS based application'
    into { file("${project.buildDir}/install/${project.name}") }
    with jposCopySpec
}

