apply plugin: 'com.android.application'

sourceCompatibility = "7"
targetCompatibility = "7"

android {
    compileSdkVersion androidCompileSdkVersion.toInteger()

    defaultConfig {
        applicationId "com.elderdrivers.riru.edxp.sandhook"
        minSdkVersion androidMinSdkVersion.toInteger()
        targetSdkVersion androidTargetSdkVersion.toInteger()
        versionCode 1
        versionName "1.0"
        multiDexEnabled false
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    ndkVersion androidCompileNdkVersion
}

dependencies {
    compileOnly project(':hiddenapi-stubs')
    implementation project(':edxp-common')
    implementation project(':sandhook-hooklib')
    compileOnly files(project(":dexmaker").tasks.getByName("makeJarRelease").outputs)
}


preBuild.doLast {
    def imlFile = file(project.name + ".iml")
    try {
        def parsedXml = (new groovy.util.XmlParser()).parse(imlFile)
        def jdkNode = parsedXml.component[1].orderEntry.find { it.'@type' == 'jdk' }
        parsedXml.component[1].remove(jdkNode)
        def sdkString = "Android API " + android.compileSdkVersion.substring("android-".length()) + " Platform"
        new groovy.util.Node(parsedXml.component[1], 'orderEntry', ['type': 'jdk', 'jdkName': sdkString, 'jdkType': 'Android SDK'])
        groovy.xml.XmlUtil.serialize(parsedXml, new FileOutputStream(imlFile))
    } catch (FileNotFoundException e) {
        // nop, iml not found
    }
}

afterEvaluate {

    tasks.withType(JavaCompile) {
        options.compilerArgs.add("-Xbootclasspath/p:${hiddenApiStubJarFilePath}")
    }

    android.applicationVariants.all { variant ->

        def variantNameCapped = variant.name.capitalize()
        def variantNameLowered = variant.name.toLowerCase()
        def myTemplatePath = "${projectDir}/template_override/"

        task("copyDex${variantNameCapped}", type: Copy) {
            dependsOn "assemble${variantNameCapped}"
            dependsOn tasks.getByPath(":edxp-common:copyCommonProperties")
            dependsOn tasks.getByPath(":sandhook-hooklib:copySandHook${variantNameCapped}LibraryToMagiskTemplate")
            def dexOutPath = variant.name.contains("release") ?
                    "${buildDir}/intermediates/dex/${variantNameLowered}/minify${variantNameCapped}WithR8" :
                    "${buildDir}/intermediates/dex/${variantNameLowered}/mergeDex${variantNameCapped}"
            from(dexOutPath) {
                rename "classes.dex", "sandhook.dex"
            }
            destinationDir file(zipPathMagiskReleasePath + "system/framework/")
            doLast {
                copy {
                    from file(myTemplatePath)
                    into file(zipPathMagiskReleasePath)
                }
            }
        }
    }
}