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

@SuppressWarnings(["GrMethodMayBeStatic", "GroovyUnusedDeclaration"])
def isReleaseBuild() {
    return !VERSION_NAME.contains("SNAPSHOT")
}

def isAndroidProject() {
    return project.getPlugins().hasPlugin('com.android.application') || project.getPlugins().hasPlugin('com.android.library')
}

def isLocal() {
    return hasProperty('local') ? Boolean.parseBoolean(getProperty('local')) : true
}

def getReleaseRepositoryUrl() {
    if (this.isLocal()) {
        return hasProperty('RELEASE_REPOSITORY_LOCAL') ? RELEASE_REPOSITORY_LOCAL : "file://${System.env.HOME}/.m2/repository"
    } else {
        return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL : "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
    }
}

def getSnapshotRepositoryUrl() {
    if (this.isLocal()) {
        return hasProperty('SNAPSHOT_REPOSITORY_LOCAL') ? SNAPSHOT_REPOSITORY_LOCAL : "file://${System.env.HOME}/.m2/repository"
    } else {
        return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL : "https://oss.sonatype.org/content/repositories/snapshots/"
    }
}

def getRepositoryUsername() {
    return hasProperty('SONATYPE_USERNAME') ? SONATYPE_USERNAME : ""
}

def getRepositoryPassword() {
    return hasProperty('SONATYPE_PASSWORD') ? SONATYPE_PASSWORD : ""
}

if (isAndroidProject()) {
    android.libraryVariants.all { variant ->
        variant.outputs.each { output ->
            File outputFile = output.outputFile
            if (outputFile != null && outputFile.name.endsWith('.aar') && 'release' == variant.buildType.name) {
                output.outputFileName = "${project.archivesBaseName}-${version}.aar"
            }
        }
    }
}

version = VERSION_NAME

artifacts {
    archives file("$buildDir/outputs/jar/${project.archivesBaseName}-${project.version}-sources.jar")
    archives file("$buildDir/outputs/jar/${project.archivesBaseName}-${project.version}-javadoc.jar")
}

afterEvaluate { project ->
    uploadArchives {
        //noinspection GradleMisplacedStatement
        repositories {
            //noinspection GroovyAssignabilityCheck
            mavenDeployer {
                beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }

                pom.groupId = 'com.evernote'
                pom.artifactId = POM_ARTIFACT_ID
                pom.version = VERSION_NAME

                repository(url: this.getReleaseRepositoryUrl()) {
                    authentication(userName: this.getRepositoryUsername(), password: this.getRepositoryPassword())
                }
                snapshotRepository(url: this.getSnapshotRepositoryUrl()) {
                    authentication(userName: this.getRepositoryUsername(), password: this.getRepositoryPassword())
                }

                pom.project {
                    name POM_NAME
                    packaging POM_PACKAGING
                    description 'Android library to save object states into a bundle.'
                    url 'https://github.com/evernote/android-state'
                    inceptionYear '2017'

                    scm {
                        url 'https://github.com/evernote/android-state'
                        connection 'scm:git:git://github.com/evernote/android-state.git'
                        developerConnection 'scm:git:git@github.com:evernote/android-state.git'
                    }

                    developers {
                        developer {
                            name 'Ralf Wondratschek'
                            email 'rwondratschek@evernote.com'
                            id 'rwondratschek'
                            url 'http://vrallev.net'
                            timezone '+1'
                            roles {
                                role 'developer'
                            }
                        }
                    }

                    licenses {
                        license {
                            name 'Eclipse Public License - v 1.0'
                            url 'https://github.com/evernote/android-state/blob/master/LICENSE'
                            distribution 'repo'
                        }
                    }

                    issueManagement {
                        system 'GitHub Issues'
                        url 'https://github.com/evernote/android-state/issues'
                    }
                }
            }
        }
    }

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

project.tasks.whenTaskAdded { task ->
    if (task.name == 'signArchives') {
        this.addSourcesAndJavadocTask task
    }
}

def addSourcesAndJavadocTask(Task uploadTask) {
    if (this.isAndroidProject()) {
        android.libraryVariants.all { variant ->
            // javadoc jar
            project.task("${variant.name.capitalize()}Javadoc", type: Javadoc) {
                failOnError true

                destinationDir = new File("$project.buildDir/javadoc/$variant.name")

                source = variant.javaCompile.source

                ext.androidJar = "${project.android.sdkDirectory}/platforms/${project.android.compileSdkVersion}/android.jar"

                options {
                    linksOffline("http://d.android.com/reference", "${project.android.sdkDirectory}/docs/reference")
                    links("http://docs.oracle.com/javase/7/docs/api/")
                    setMemberLevel(JavadocMemberLevel.PACKAGE)
                    addStringOption('Xdoclint:none', '-quiet')
                    docEncoding = 'UTF-8'
                    encoding = 'UTF-8'
                    charSet = 'UTF-8'
                }

                exclude '**/BuildConfig.java'
                exclude '**/R.java'
            }

            project.task("generate${variant.name.capitalize()}JavadocJar", type: Jar, dependsOn: "${variant.name.capitalize()}Javadoc") {
                classifier 'javadoc'

                description = 'Assembles a jar archive containing the generated Javadoc API documentation of $variant.name.'

                destinationDir = new File("$project.buildDir/outputs/jar/")

                exclude '**/BuildConfig.class'
                exclude '**/R.class'

                from "$project.buildDir/javadoc/$variant.name"
            }

            // sources jar
            project.task("generate${variant.name.capitalize()}SourcesJar", type: Jar) {
                classifier = 'sources'

                description = 'Assembles a jar archive containing the main sources of $variant.name..'

                destinationDir = new File("$project.buildDir/outputs/jar/")

                // exclude generated files
                exclude '**/BuildConfig.java'
                exclude '**/R.java'

                from variant.javaCompile.source
            }

            if (variant.name.equalsIgnoreCase('release')) {
                uploadTask.dependsOn project.tasks.getByName("assemble${variant.name.capitalize()}")
                uploadTask.dependsOn project.tasks.getByName("generate${variant.name.capitalize()}JavadocJar")
                uploadTask.dependsOn project.tasks.getByName("generate${variant.name.capitalize()}SourcesJar")
            }
        }
    } else {
        task sourcesJar(type: Jar, dependsOn: classes) {
            classifier = 'sources'
            destinationDir = new File("$project.buildDir/outputs/jar/")
            from sourceSets.main.allSource
        }

        task javadocJar(type: Jar, dependsOn: javadoc) {
            classifier = 'javadoc'
            destinationDir = new File("$project.buildDir/outputs/jar/")
            from javadoc.destinationDir
        }

        if (JavaVersion.current().isJava8Compatible()) {
            allprojects {
                tasks.withType(Javadoc) {
                    options.addStringOption('Xdoclint:none', '-quiet')
                }
            }
        }

        uploadTask.dependsOn project.tasks.getByName("jar")
        uploadTask.dependsOn project.tasks.getByName("javadocJar")
        uploadTask.dependsOn project.tasks.getByName("sourcesJar")
    }
}