apply plugin: 'maven-publish'
apply plugin: 'signing'
apply from: './publish-pom.gradle'

String TARGET_MAVEN_CENTRAL_URL = 'https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/'

List DEVELOPERS = [
    [name: 'd4vidi', email: 'amit.d4vidi@gmail.com'],
]

String _sonatypeUsername = 'd4vidi'
String _sonatypePassword = System.getProperty('sonatypePassword')
String _versionName = System.getProperty('version')
String _mavenRepoUrl = TARGET_MAVEN_CENTRAL_URL
Map _mavenCredentials = [
        username: _sonatypeUsername,
        password: _sonatypePassword,
]
def _selectedVariant = null

def onPrePublish = {
    assertDefined(_versionName, "Publishing: Version not specified (run 'gradle publish' with a -Dversion=1.2.3 argument)")
    assertDefined(_sonatypePassword, "Publishing: Please specify the password to use for sonatype (run 'gradle publish' with a -DsonatypePassword=<pw> argument)")
    logger.lifecycle("Publishing is now in session! 📣\n  Version: $_versionName\n  Target URL: ${_mavenRepoUrl}\n  Build-variant: '${_selectedVariant.name}'")
}

def declareArchive = { target ->
    project.artifacts {
        archives target
    }
}

// Running from Gradle tab in IDE would create liboverscroll/build/libs/liboverscroll-sources.jar
task sourcesJar(type: Jar) {
    from android.sourceSets.main.java.srcDirs
    classifier = 'sources'
}

task javadoc(type: Javadoc) {
    failOnError false
    source = android.sourceSets.main.java.srcDirs
    classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
}

// Running from Gradle tab in IDE would create liboverscroll/build/libs/liboverscroll-javadoc.jar
task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from javadoc.destinationDir
}

/*
 * Signing configuration
 * https://docs.gradle.org/current/userguide/signing_plugin.html
 */

// Tell signing task to sign everything current and future we set as a project archive...
signing {
    sign configurations.archives
}

/*
 * Plumbing work for actually having the publishing task work properly, if executed
 */

project.afterEvaluate {
    project.tasks.all { Task task ->
        android.libraryVariants.all { variant ->
            String variantName = variant.name.capitalize()
            if (task.name == "publishMaven${variantName}AarPublicationToMavenRepository") {
                task.dependsOn "assemble${variantName}"
                task.dependsOn project.tasks.signArchives
                task.doFirst {
                    onPrePublish()
                }
            }
        }
    }
}

/*
 * Publishing configuration
 */

publishing {
    repositories {
        maven {
            url _mavenRepoUrl
            if (_mavenCredentials != null) {
                credentials {
                    username _mavenCredentials.username
                    password _mavenCredentials.password
                }
            }
        }
    }

    publications {
        android.libraryVariants.all { variant ->
            if (isReleaseVariant(variant)) {
                _selectedVariant = variant

                String variantNameCapitalized = variant.name.capitalize()

                "maven${variantNameCapitalized}Aar"(MavenPublication) {
                    groupId 'io.github.everythingme'
                    artifactId 'overscroll-decor-android'
                    version "$_versionName"

                    // Register built .aar as published artifact (as a file, explicitly)
                    variant.outputs.forEach { output ->
                        artifact output.outputFile

                        // Also register as an archive-artifact, for signing (via equivalent task's output)
                        declareArchive project.tasks["bundle${variantNameCapitalized}Aar"]
                    }

                    // Register sources, javadoc as published artifacts (via equivalent tasks' output)
                    artifact sourcesJar
                    artifact javadocJar

                    // Also register source, javadoc as archive-artifacts, for signing
                    declareArchive sourcesJar
                    declareArchive javadocJar

                    // Add package metadata to the .pom
                    pom {
                        name = 'Overscroll-Decor'
                        description = 'iOS-like over-scrolling effect for Android'
                        url = 'https://github.com/EverythingMe/overscroll-decor'
                        packaging 'aar' // Oh so important - or apps would ignore our code!!!!!
                        scm {
                            connection = 'scm:git:git://github.com/EverythingMe/overscroll-decor'
                            developerConnection = 'scm:git:git@github.com/EverythingMe/overscroll-decor.git'
                            url = 'https://github.com/EverythingMe/overscroll-decor'
                        }
                        licenses {
                            license {
                                name = 'BSD-2'
                                url = 'https://github.com/EverythingMe/overscroll-decor/blob/master/LICENSE'
                            }
                        }
                        developers {
                            DEVELOPERS.each { d ->
                                developer {
                                    name = d.name
                                    email = d.email
                                }
                            }
                        }
                    }

                    // Add dependencies to the .pom
                    buildPomXmlDependencies(pom, configurations)

                    // Register pom.xml's signature file (pom.xml.asc) as published artifact
                    // Note: this is done manually, instead of registering the pom as an archived artifact
                    pom.withXml {
                        def pomFile = file("${project.buildDir}/generated-pom.xml")
                        writeTo(pomFile) // Need to force-write so as to have the signature generated over the finalized content

                        def pomAscFile = signing.sign(pomFile).signatureFiles[0]
                        artifact(pomAscFile) {
                            classifier = null
                            extension = 'pom.asc'
                        }
                    }

                    // Register all artifacts we've previously registered as archives (i.e. .jar.asc's, .aar.asc's) as published artifacts.
                    // Note: this relies on preregistering the equivalent generator-tasks as archive artifacts
                    // inside a project.artifacts { ... } clause.
                    project.tasks.signArchives.signatureFiles.each {
                        artifact(it) {
                            def matcherSrcDocs = (it.file =~ /-(sources|javadoc)\.jar\.asc$/)
                            def matcherAAR = (it.file =~ /\.aar\.asc$/)
                            if (matcherSrcDocs.find()) {
                                classifier = matcherSrcDocs.group(1)
                                extension = 'jar.asc'
                            } else if (matcherAAR.find()) {
                                classifier = null
                                extension = 'aar.asc'
                            } else {
                                classifier = null
                                extension = null
                            }
                        }
                    }
                }
            }
        }
    }
}

/*
 * Utils
 */

private static def isReleaseVariant(variant) {
    return variant.buildType.name == 'release'
}

private static def assertDefined(target, message) {
    if (target == null) {
        throw new IllegalArgumentException(message)
    }
}
