/*
 * Copyright (C) 2014 Coco software (www.cocosw.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

apply plugin: 'maven'
apply plugin: 'signing'


def isReleaseBuild() {
    return version.contains("SNAPSHOT") == false
}

def sonatypeRepositoryUrl
if (isReleaseBuild()) {
    sonatypeRepositoryUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
} else {
    sonatypeRepositoryUrl = "https://oss.sonatype.org/content/repositories/snapshots/"
}

def githubRepositoryUrl
if (isReleaseBuild()) {
    githubRepositoryUrl = "file:///D:/develop/mvn"
} else {
    githubRepositoryUrl = "file:///D:/develop/mvn"
}

def local
if (project.gradle.startParameter.taskNames.contains("uploadLocal")) {
    local = true
} else {
    local = false
}


if (ext.properties.containsKey('signing.keyId') &&
        !ext.properties.containsKey('signing.password')) {
    if (System.console()) {
        ext.set('signing.password',
                System.console().readPassword("\n\$ Type in GPG key password: "))
    } else {
        ext.set('signing.password', 'pass')
    }
}

if (!ext.properties.containsKey('nexusUsername')) {
    if (System.console()) {
        ext.set('nexusUsername', new String(System.console().readPassword(
                "\n\$ Type in username for Sonatype nexus account ${nexusUsername}: ")))
    } else {
        ext.set('nexusUsername', 'user')
    }
}

if (!ext.properties.containsKey('nexusPassword')) {
    if (System.console()) {
        ext.set('nexusPassword', new String(System.console().readPassword(
                "\n\$ Type in password for Sonatype nexus account ${nexusUsername}: ")))
    } else {
        ext.set('nexusPassword', 'pass')
    }
}

afterEvaluate { project ->
    uploadArchives {
        repositories {
            mavenDeployer {
                configurePOM(pom)
                beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
                if (local != true) {
                    repository(url: sonatypeRepositoryUrl) {
                        authentication(userName: nexusUsername, password: nexusPassword)
                    }
                } else {
                    repository(url: githubRepositoryUrl)
                }
            }
        }
    }

    signing {
        required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
        sign configurations.archives
    }


    task androidJavadocs(type: Javadoc) {
        failOnError false // add this line
        source = android.sourceSets.main.java.source
        options {
            links "http://docs.oracle.com/javase/7/docs/api/"
            linksOffline "http://d.android.com/reference", "${android.sdkDirectory}/docs/reference"
        }
        classpath += project.android.libraryVariants.toList().first().javaCompile.classpath
        classpath += project.files(android.getBootClasspath().join(File.pathSeparator))

    }

    task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
        classifier = 'javadoc'
        from androidJavadocs.destinationDir
    }

    task androidSourcesJar(type: Jar) {
        classifier = 'sources'
        from android.sourceSets.main.java.srcDirs
    }

    task uploadLocal {
        dependsOn { uploadArchives }
    }

    task apklib(type: Zip) {
        appendix = extension = 'apklib'

        from 'AndroidManifest.xml'
        into('res') {
            from 'res'
        }
        into('src') {
            from 'src'
        }
    }

    artifacts {
        //    archives jarRelease
        archives androidSourcesJar
        archives androidJavadocsJar
        archives apklib
    }
}

private configurePOM(def pom) {
    pom.project {
        groupId POM_GROUP_ID
        artifactId POM_ARTIFACT_ID
        version POM_VERSION
        name POM_NAME
        packaging POM_PACKAGING
        description POM_DESCRIPTION
        url POM_URL
        inceptionYear POM_INCEPTION_YEAR

        scm {
            url POM_SCM_URL
            connection POM_SCM_CONNECTION
            developerConnection POM_SCM_DEV_CONNECTION
        }

        licenses {
            license {
                name POM_LICENCE_NAME
                url POM_LICENCE_URL
                distribution POM_LICENCE_DIST
                comments POM_LICENCE_COMMENTS
            }
        }

        developers {
            developer {
                id POM_DEVELOPER_ID
                name POM_DEVELOPER_NAME
                email POM_DEVELOPER_EMAIL
                url POM_DEVELOPER_URL
            }
        }

        issueManagement {
            system POM_ISSUE_MANAGEMENT_SYSTEM
            url POM_ISSUE_MANAGEMENT_URL
        }
    }
}
