final var cdkVersion = {
    var props = new Properties()
    file("core/src/main/resources/version.properties").withInputStream(props::load)
    return props.getProperty('version', 'undefined')
}()

allprojects {
    apply plugin: 'java-library'
    apply plugin: 'maven-publish'

    group 'io.airbyte.cdk'

    project.version = cdkVersion

    publishing {
        publications {
            cdk(MavenPublication) {
                from components.java
            }
        }
        // This repository is only defined and used in the context of an artifact publishing
        // It's different from the 'airbyte-public-jars' defined in settings.graddle only in its omission
        // of the 'public' directory. Any artifacts publish here will be available in the 'airbyte-public-jars' repo
        repositories {
            maven {
                name 'airbyte-repo'
                url 'https://airbyte.mycloudrepo.io/repositories/airbyte-public-jars/'
                credentials {
                    username System.getenv('CLOUDREPO_USER')
                    password System.getenv('CLOUDREPO_PASSWORD')
                }
            }
        }
    }

    // This is necessary because the mockit.kotlin any() generates a bunch of bad casts
    spotbugsTest.omitVisitors = ['FindBadCast2']
}

description = "Airbyte Connector Development Kit (CDK) for Java."

tasks.register('cdkBuild').configure {
    dependsOn subprojects.collect { it.tasks.named('build') }
}
tasks.register('cdkPublish').configure {
    dependsOn subprojects.collect { it.tasks.named('publish') }
}
tasks.register('assertCdkVersionNotPublished') {
    doLast {

        var repoUrl = "https://airbyte.mycloudrepo.io/public/repositories/airbyte-public-jars"
        var groupIdUrl = "${repoUrl}/io/airbyte/cdk"
        var artifactUrl = "${groupIdUrl}/airbyte-cdk-core/${project.version}/airbyte-cdk-core-${project.version}.pom"

        var connection = artifactUrl.toURL().openConnection() as HttpURLConnection
        connection.setRequestMethod("HEAD")
        connection.connect()

        var responseCode = connection.getResponseCode()

        if (responseCode == 200) {
            throw new GradleException("Java CDK '${project.version}' already published at ${groupIdUrl}")
        } else if (responseCode == 404) {
            logger.lifecycle("Java CDK '${project.version}' not yet published at ${groupIdUrl}")
        } else {
            throw new GradleException("Unexpected HTTP response code ${responseCode} from ${artifactUrl} : expected either 200 or 404.")
        }
    }
}
