buildscript{
    repositories{
        mavenLocal()
        mavenCentral()
        google()
        maven{ url "https://oss.sonatype.org/content/repositories/snapshots/" }
        jcenter()
    }

    dependencies{
        //IMPORTANT NOTICE: any version of the plugin after 3.4.1 will break builds
        //it appears abstract methods don't get desugared properly (if at all)
        classpath 'com.android.tools.build:gradle:3.4.1'
    }
}

apply plugin: "com.android.application"

configurations{ natives }

repositories{
    mavenCentral()
    jcenter()
    maven{ url "https://maven.google.com" }
}

dependencies{
    implementation project(":core")

    implementation arcModule("backends:backend-android")
    implementation 'com.jakewharton.android.repackaged:dalvik-dx:9.0.0_r3'

    natives "com.github.Anuken.Arc:natives-android:${getArcHash()}"
    natives "com.github.Anuken.Arc:natives-freetype-android:${getArcHash()}"
    natives "com.github.Anuken.Arc:natives-box2d-android:${getArcHash()}"

    //android dependencies magically disappear during compilation, thanks gradle!
    if(new File(projectDir.parent, '../Arc').exists()) compileOnly fileTree(dir: '../../Arc/backends/backend-android/libs', include: ['*.jar'])
}

task deploy(type: Copy){
    dependsOn "assembleRelease"

    from "build/outputs/apk/release/android-release.apk"
    into "../deploy/"
    rename("android-release.apk", "${generateDeployName('android')}.apk")
}

android{
    buildToolsVersion '29.0.3'
    compileSdkVersion 29
    sourceSets{
        main{
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets', 'src/main/assets', '../core/assets/']
            jniLibs.srcDirs = ['libs']
        }

        androidTest.setRoot('tests')
    }
    packagingOptions{
        exclude 'META-INF/robovm/ios/robovm.xml'
    }

    defaultConfig{
        Properties props = loadVersionProps()
        Integer vcode = props['androidBuildCode']?.toInteger() ?: 1
        def versionNameResult = "$versionNumber-$versionType-${getBuildVersion().replace(" ", "-")}"

        applicationId "io.anuke.mindustry"
        minSdkVersion 14
        targetSdkVersion 29
        
        versionName versionNameResult
        versionCode = (System.getenv("TRAVIS_BUILD_ID") != null ? System.getenv("TRAVIS_BUILD_ID").toInteger() : vcode)

        if(project.hasProperty("release")){
            props['androidBuildCode'] = (vcode + 1).toString()
        }
        props.store(file('../core/assets/version.properties').newWriter(), null)
    }

    compileOptions{
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    flavorDimensions "google"

    signingConfigs{
        release{
            if(project.hasProperty("RELEASE_STORE_FILE")){
                storeFile file(RELEASE_STORE_FILE)
                storePassword RELEASE_STORE_PASSWORD
                keyAlias RELEASE_KEY_ALIAS
                keyPassword RELEASE_KEY_PASSWORD
            }else if(System.getenv("CI") == "true"){
                storeFile = file("../../bekeystore.jks")
                storePassword = System.getenv("keystore_password")
                keyAlias = System.getenv("keystore_alias")
                keyPassword = System.getenv("keystore_alias_password")
            }else{
                println("No keystore property found. Releases will be unsigned.")
            }
        }
    }

    if(project.hasProperty("RELEASE_STORE_FILE") || System.getenv("CI") == "true"){
        buildTypes{
            release{
                signingConfig signingConfigs.release
            }
        }
    }
}
// called every time gradle gets executed, takes the native dependencies of
// the natives configuration, and extracts them to the proper libs/ folders
// so they get packed with the APK.
task copyAndroidNatives(){
    configurations.natives.files.each{ jar ->
        copy{
            from zipTree(jar)
            into file("libs/")
            include "**"
        }
    }
}

task run(type: Exec){
    def path
    def localProperties = project.file("../local.properties")
    if(localProperties.exists()){
        Properties properties = new Properties()
        localProperties.withInputStream{ instr ->
            properties.load(instr)
        }
        def sdkDir = properties.getProperty('sdk.dir')
        if(sdkDir){
            path = sdkDir
        }else{
            path = "$System.env.ANDROID_HOME"
        }
    }else{
        path = "$System.env.ANDROID_HOME"
    }

    def adb = path + "/platform-tools/adb"
    commandLine "$adb", 'shell', 'am', 'start', '-n', 'io.anuke.mindustry/mindustry.android.AndroidLauncher'
}
