import java.util.regex.Pattern

apply plugin: 'com.android.library'
apply plugin: 'signing'

// Before configuring, make sure libcrypto is installed
preBuild {
    println('Installing libcrypto prebuilt binaries')
    def exec = (project.file('fetch_libcrypto.sh').absolutePath).execute()
    exec.waitForProcessOutput(System.out, System.err)
}

Properties getGitTag() {
    def gitTag = "git describe --tags".execute().text.trim()
    def version = new Properties()
    def versionPattern = Pattern.compile('v(\\d+).(\\d+).(\\d+)(-(.+))?')
    def matcher = versionPattern.matcher(gitTag)
    if (matcher.matches()) {
        version['major'] = matcher.group(1)
        version['minor'] = matcher.group(2)
        version['patch'] = matcher.group(3)
        try {
            version['tag'] = matcher.group(5)
        } catch (Exception ex) {}
    }
    return version
}

ext {
    gitVersionName = {
        def version = getGitTag()
        def name = "${version['major']}.${version['minor']}.${version['patch']}"
        return name
    }
    gitVersionCode = {
        def version = getGitTag()
        try {
            def major = version['major'] as int
            def minor = version['minor'] as int
            def patch = version['patch'] as int
            return (major * 1000) + (minor * 100) + patch
        } catch (Exception ex) {
            return 0
        }
    }
    gitVersionTag = {
        def version = getGitTag()
        return version['tag'] != '' ? '-' + version['tag'] : version['tag']
    }
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"
    ndkVersion "21.4.7075529" // LTS version

    useLibrary 'android.test.runner'
    useLibrary 'android.test.base'
    useLibrary 'android.test.mock'

    defaultConfig {
        minSdkVersion 24  // TODO - dictated by CompletableFuture which is API 24+
        targetSdkVersion 30
        versionCode = gitVersionCode()
        versionName = gitVersionName()

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        consumerProguardFiles 'consumer-rules.pro'

        ndk {
            abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64"
        }

        externalNativeBuild {
            cmake {
                arguments "-DBUILD_DEPS=ON"
            }
        }
    }

    sourceSets {
        main {
            java.srcDir '../../src/main/java'
            java.srcDir 'src/main/java'
        }
        androidTest {
            setRoot '../../src/test'
            java.srcDir '../../src/test/java'
            java.srcDir 'src/androidTest/java'
            assets.srcDir 'src/androidTest/assets'
        }
    }

    buildTypes {
        debug {
            versionNameSuffix = gitVersionTag()
            buildConfigField("String", "VERSION_NAME", "\"" + gitVersionName() + "\"")
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            versionNameSuffix ""
            buildConfigField("String", "VERSION_NAME", "\"" + gitVersionName() + "\"")
        }
    }

    externalNativeBuild {
        cmake {
            path "../../CMakeLists.txt"
            buildStagingDirectory "../../target/cmake-build"
            version "3.10.2"
        }
    }

    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
        // Enable desugaring so that Android lint doesn't flag `java.time` usage. Downstream
        // consumers will need to enable desugaring to use this library.
        // See: https://developer.android.com/studio/write/java8-support#library-desugaring
        coreLibraryDesugaringEnabled true
    }
}

build.dependsOn preBuild

dependencies {
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
    androidTestImplementation 'org.mockito:mockito-core:3.11.2'
    androidTestImplementation 'androidx.appcompat:appcompat:1.3.1'
    androidTestImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test:runner:1.4.0'
    androidTestImplementation 'androidx.test:monitor:1.4.0@aar'
    androidTestImplementation 'androidx.test:rules:1.4.0'
}

// Publishing
apply plugin: 'maven-publish'

// Sources
task androidSourcesJar(type: Jar) {
    archiveClassifier.set('sources')
    from android.sourceSets.main.java.srcDirs
}

// Docs
task androidDocs(type: Javadoc) {
    source = android.sourceSets.main.java.srcDirs
    classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
    android.libraryVariants.all { variant ->
        if (variant.name == 'release') {
            owner.classpath += variant.javaCompileProvider.get().classpath
        }
    }
    exclude '**/R.html', '**/R.*.html', '**/index.html'
}

task androidDocsJar(type: Jar) {
    archiveClassifier.set('javadoc')
    from androidDocs.destinationDir
}


afterEvaluate {
    publishing {
        repositories {
            maven { name = "testLocal"; url = "$rootProject.buildDir/m2" }
        }

        publications {
            release(MavenPublication) {
                from components.release

                groupId = 'software.amazon.awssdk.crt'
                artifactId = 'aws-crt-android'
                version = project.hasProperty('newVersion') ? project.property('newVersion') : android.defaultConfig.versionName

                pom {
                    name.set("software.amazon.awssdk.crt:aws-crt-android")
                    description.set("Java Android bindings for the AWS SDK Common Runtime")
                    url.set("https://github.com/awslabs/aws-crt-java")
                    licenses {
                        license {
                            name.set("The Apache License, Version 2.0")
                            url.set("http://www.apache.org/licenses/LICENSE-2.0.txt")
                        }
                    }

                    developers {
                        developer {
                            id.set("aws-sdk-common-runtime")
                            name.set("AWS SDK Common Runtime Team")
                            email.set("aws-sdk-common-runtime@amazon.com")
                        }
                    }

                    scm {
                        connection.set("scm:git:git://github.com/awslabs/aws-crt-java.git")
                        developerConnection.set("scm:git:ssh://github.com/awslabs/aws-crt-java.git")
                        url.set("https://github.com/awslabs/aws-crt-java")
                    }
                }
            }
        }

        repositories {
            maven {
                def snapshotRepo = "https://aws.oss.sonatype.org/content/repositories/snapshots"
                def releaseRepo = "https://aws.oss.sonatype.org/"
                url = version.endsWith('SNAPSHOT') ? snapshotRepo : releaseRepo
            }
        }

        if (project.hasProperty("signingKey") && project.hasProperty("signingPassword")) {
            signing {
                useInMemoryPgpKeys(
                        (String) project.property("signingKey"),
                        (String) project.property("signingPassword")
                )
                println("key=" + project.property("signingKey"))
                sign(publications)
            }
        }
    }
}
