apply plugin: "maven-publish"
apply plugin: "signing"
apply from: "${rootDir}/common/constants.gradle"

group = PUBLISH_GROUP_ID
version = PUBLISH_VERSION

task androidSourcesJar(type: Jar) {
    archiveClassifier.set("sources")

    if (project.plugins.findPlugin("com.android.library")) {
        from android.sourceSets.main.java.srcDirs
        from android.sourceSets.main.kotlin.srcDirs
    } else {
        from sourceSets.main.java.srcDirs
        from sourceSets.main.kotlin.srcDirs
    }
}

artifacts {
    archives androidSourcesJar
}

afterEvaluate {
    publishing {
        publications {
            release(MavenPublication) {
                groupId PUBLISH_GROUP_ID
                artifactId PUBLISH_ARTIFACT_ID
                version PUBLISH_VERSION

                if (project.plugins.findPlugin("com.android.library")) {
                    from components.release
                } else {
                    from components.java
                }

                artifact androidSourcesJar

                pom {
                    name = PUBLISH_ARTIFACT_ID
                    description = PUBLISH_ARTIFACT_DESCRIPTION
                    url = releaseWebsite

                    licenses {
                        license {
                            name = licenseName
                            url = licenseUrl
                        }
                    }

                    developers {
                        developer {
                            id = developerId
                            name = developerName
                            email = developerEmail
                        }
                    }

                    scm {
                        connection = scmConnection
                        developerConnection = scmDeveloperConnection
                        url = siteUrl
                    }
                }
            }
        }

        repositories {
            maven {
                name = publishingHostRepoName
                url = uri(publishingHostRepoUrl)

                credentials {
                    username = getPropertyOrDefault("SONATYPE_NEXUS_USERNAME", System.getenv("SONATYPE_NEXUS_USERNAME"))
                    password = getPropertyOrDefault("SONATYPE_NEXUS_PASSWORD", System.getenv("SONATYPE_NEXUS_PASSWORD"))
                }
            }
        }
    }

    signing {
        sign publishing.publications
    }
}

private def getPropertyOrDefault(key, defaultValue) {
    def foundProperty = properties[key]
    return ((foundProperty != null) ? foundProperty : defaultValue)
}