
import org.apache.tools.ant.taskdefs.condition.Os

String findCommand(String dir, String command) {
    def extension = Os.isFamily(Os.FAMILY_WINDOWS) ? ".exe" : ""
    def cmd = "$dir/$command$extension"
    if (! new File(cmd).exists()) {
        throw new Exception("Command $command not found in dir $dir")
    }
    cmd
}

String findJavaCommand(String command) {
    def jh = System.getenv("JAVA8_HOME")
    if (jh == null) {
        throw new Exception("Environment variable JAVA8_HOME not set")
    }
    findCommand("$jh/bin", command)
}

Boolean doSigning(String signingAllowed, Boolean doModule) {
    def b = signingAllowed.trim() == "true" && doModule
//    println("signModule: ${project.name} signingAllowed: $signingAllowed doModule: $doModule")
    b
}

void performSigning(String signingAllowed, Boolean doModule) {
    signing {
        required { doSigning(signingAllowed, doModule) }
        sign configurations.archives
    }
}

def customisePom(pom, gradleProject) {
    pom.withXml {
        def root = asNode()

        // add all items necessary for maven central publication
        root.children().last() + {
            resolveStrategy = Closure.DELEGATE_FIRST

            name project.pomProjectName
            description project.projectDescription
            url project.projectUrl
            organization {
                name project.pomOrganisation
                url project.projectUrl
            }
            issueManagement {
                system 'GitHub'
                url project.issueUrl
            }
            licenses {
                license {
                    name project.licenseName
                    url project.licenseUrl
                    distribution 'repo'
                }
            }
            scm {
                url project.githubUrl
                connection project.scmGitFile
                developerConnection project.scmSshGitFile
            }
        }
    }
}


void configureUpload(String signingEnabled, Boolean signModule, Boolean uploadModule) {

    if (uploadModule) {

        publishing {

            publications {

                mavenJava(MavenPublication) {
                    groupId project.group
                    artifactId project.name
                    version project.version

                    from components.java

                    customisePom(pom, rootProject)

                    artifact sourcesJar
                    artifact javadocJar

                    if (doSigning(signingEnabled, signModule)) {
                        // sign the pom
                        pom.withXml {
                            def pomFile = file("${project.buildDir}/generated-pom.xml.asc")
                            writeTo(pomFile)
                            def pomAscFile = signing.sign(pomFile).signatureFiles[0]
                            artifact(pomAscFile) {
                                classifier = null
                                extension = 'pom.asc'
                            }
                            pomFile.delete()
                        }

                        // sign the artifacts
                        project.tasks.signArchives.signatureFiles.each {
                            artifact(it) {
                                def matcher = it.file =~ /-(sources|javadoc|jre8|jre9)\.jar\.asc$/
                                if (matcher.find()) {
                                    classifier = matcher.group(1)
                                } else {
                                    classifier = null
                                }
                                extension = 'jar.asc'
                            }
                        }
                    }

                }

            }

            repositories {
                maven {
                    url project.sonatypeUploadUrl
                    credentials {
                        username sonatypeUsername
                        password sonatypePassword
                    }
                }
            }

        }

        model {
            tasks.publishMavenJavaPublicationToMavenLocal {
                dependsOn(project.tasks.signArchives)
            }
            tasks.publishMavenJavaPublicationToMavenRepository {
                dependsOn(project.tasks.signArchives)
            }
            tasks.publish {
                dependsOn(project.tasks.build)
            }
//        tasks.install {
//            dependsOn(project.tasks.build)
//        }
        }

    }

}

ext {
    findJavaCommand = this.&findJavaCommand
    doSigning = this.&doSigning
    performSigning = this.&performSigning
    configureUpload = this.&configureUpload
}
