import java.text.SimpleDateFormat

plugins {
    id "org.jetbrains.kotlin.jvm" version "1.9.20"
    id "com.jfrog.artifactory" version "4.29.2"
    id "biz.aQute.bnd.builder" version "6.3.1"
    id "com.bnorm.power.kotlin-power-assert" version "0.13.0"
}

allprojects {
    java {
        toolchain {
            languageVersion = JavaLanguageVersion.of(11)
        }
    }
    kotlin {
        jvmToolchain {
            languageVersion = JavaLanguageVersion.of(11)
        }
    }
}

def getDevelopmentVersion() {
    def output = new StringBuilder()
    def error = new StringBuilder()
    def gitShortHash = ["git", "-C", projectDir.toString(), "rev-parse", "--short", "HEAD"].execute()
    gitShortHash.waitForProcessOutput(output, error)
    def gitHash = output.toString().trim()
    if (gitHash.isEmpty()) {
        println "Git hash is empty: error: ${error.toString()}"
        throw new IllegalStateException("Git hash could not be determined")
    }
    def version = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss").format(new Date()) + "-" + gitHash
    println "Created development version: $version"
    version
}

def releaseVersion = System.env.RELEASE_VERSION
version = releaseVersion ? releaseVersion : getDevelopmentVersion()
group = "com.atlassian"
allprojects {
    description = "Nadel is a Kotlin library that combines multiple GraphQL services together into one GraphQL API."
}
gradle.buildFinished { buildResult ->
    println "*******************************"
    println "*"
    if (buildResult.failure != null) {
        println "* FAILURE - ${buildResult.failure}"
    } else {
        println "* SUCCESS"
    }
    println "* Version: $version"
    println "*"
    println "*******************************"
}

allprojects {
    repositories {
        mavenLocal()
        mavenCentral()
    }
}

subprojects {
    // Don't publish test
    if (project.name == "test") {
        return
    }

    apply plugin: "java"
    apply plugin: "java-library"
    apply plugin: "signing"
    apply plugin: "maven-publish"
    apply plugin: "com.jfrog.artifactory"

    task sourcesJar(type: Jar) {
        dependsOn classes
        archiveClassifier = "sources"
        from sourceSets.main.allSource
    }

    task javadocJar(type: Jar, dependsOn: javadoc) {
        archiveClassifier = "javadoc"
        from javadoc.destinationDir
    }

    publishing {
        publications {
            nadel(MavenPublication) {
                from components.java

                artifact sourcesJar {
                    archiveClassifier = "sources"
                }
                artifact javadocJar {
                    archiveClassifier = "javadoc"
                }

                // This used to be in settings.gradle but it seems that Kotlin gets angry when you rename the project name
                // It gets angry in the sense that it doesn't think the test/ and main/ src sets are in the same module
                // And members with internal modifier in main/ can't be seen in test/
                def projectName = project.name == "lib" ? "nadel" : project.name

                groupId rootProject.group
                artifactId projectName
                version rootProject.version
                pom.withXml {
                    asNode().children().last() + {
                        resolveStrategy = Closure.DELEGATE_FIRST
                        name projectName
                        description project.description
                        url "https://github.com/atlassian-labs/nadel"
                        scm {
                            url "https://github.com/atlassian-labs/nadel"
                            connection "https://github.com/atlassian-labs/nadel"
                            developerConnection "https://github.com/atlassian-labs/nadel"
                        }
                        licenses {
                            license {
                                name "Apache License 2.0"
                                url "https://www.apache.org/licenses/"
                                distribution "repo"
                            }
                        }
                        developers {
                            developer {
                                id "andimarek"
                                name "Andreas Marek"
                            }
                        }
                    }
                }
            }
        }
    }

    tasks.withType(PublishToMavenRepository) {
        dependsOn(build)
    }

    signing {
        if (System.getenv("SIGNING_KEY") != null) {
            useInMemoryPgpKeys(System.getenv("SIGNING_KEY"), System.getenv("SIGNING_PASSWORD"))
            sign(publishing.publications)
        }
    }

    javadoc {
        options.encoding = "UTF-8"
    }

    artifacts {
        archives sourcesJar
        archives javadocJar
    }

    artifactory {
        publish {
            setContextUrl("https://packages.atlassian.com/")

            repository {
                repoKey = "maven-central"
                username = System.env.ARTIFACTORY_USERNAME
                password = System.env.ARTIFACTORY_API_KEY
            }
            defaults {
                publications("nadel")
                publishIvy = false
                // This needs to be "false", otherwise, the artifactory plugin will try to publish
                // a build info file to Artifactory and fail because we don't have the permissions to do that.
                publishBuildInfo = false
            }
        }
    }
}

configurations {
    ktlint
}

dependencies {
    ktlint "com.pinterest:ktlint:0.39.0"
}

task ktlintFormat(type: JavaExec, group: "formatting") {
    description = "Fix Kotlin code style deviations"
    classpath = configurations.ktlint
    main = "com.pinterest.ktlint.Main"
    args "-F", "src/**/*.kt"
}

task ktlintSetCodeStyle(type: JavaExec) {
    description = "Apply Kotlin formatter style"
    classpath = configurations.ktlint
    main = "com.pinterest.ktlint.Main"
    args "applyToIDEAProject", "-y"
}
