project.ext.preDexLibs = !project.hasProperty('disablePreDex')
println('PREDEX ' + (project.ext.preDexLibs ? 'ENABLED' : 'DISABLED'))

// 禁用以解决tingyun打包失败等问题
// project.plugins.whenPluginAdded { plugin ->
//     if ("com.android.build.gradle.AppPlugin".equals(plugin.class.name)) {
//         project.android.dexOptions.preDexLibraries = rootProject.ext.preDexLibs
//     } else if ("com.android.build.gradle.LibraryPlugin".equals(plugin.class.name)) {
//         project.android.dexOptions.preDexLibraries = rootProject.ext.preDexLibs
//     }
// }

buildscript {

    def mavenUrl=System.getenv("GRADLE_M2_HOME");
    if(mavenUrl==null){
        println("AppCanPkgError: GRADLE_M2_HOME mavenUrl is null. Not Supported Environment.");
    }
    repositories {
        maven {
            url mavenUrl
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.2'
    }
}

apply plugin: 'com.android.application'

//apply from : "rewriterPlugin.gradle"
buildscript {
//    project.ext.set("rewriterPluginName", "");
//    project.ext.set("rewriterGradlePluginDir", "");
    project.ext{
        rewriterPluginName = "";
        rewriterGradlePluginDir = "";
    }
    try{
        String currentPath = "." + File.separator;
        File currentFile = new File(currentPath).getAbsoluteFile();//当前所在目录地址
        println("rewriter---currentFile: " + currentFile.getPath());
        File parentDir = currentFile.getParentFile().getParentFile();//上上级目录地址
        String parentPath = parentDir.getAbsolutePath();
        String randomName = parentDir.getName();//获取随机名称
        File pluginsDir = new File(parentPath + File.separator +randomName);
        String pluginsPath = pluginsDir.getAbsolutePath();
        println("rewriter---pluginsPath: " + pluginsPath);
        String[] params = new String[4];//{"find", pluginsPath, "-name", "class.rewriter.jar"}
        params[0] = "find";
        params[1] = pluginsPath;
        params[2] = "-name";
        params[3] = "class.rewriter.jar";
        Process p = Runtime.getRuntime().exec(params);
        InputStream is = p.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line = null;
        int count = 0;
        while((line = reader.readLine())!= null){
            println("rewriter---execResult: " + line);
            File rewriterJar = new File(line);
            File rewriterDir = rewriterJar.getParentFile();
            if("rewriter".equals(rewriterDir.getName())){
                count++;
                if(count > 1){ 
                    println("rewriter---found more than one rewriter plugin, will only use the last one!");
                }
                //目录结构正确，获取插件名称
                String rewriterGradlePluginDir = rewriterDir.getAbsolutePath();
                project.ext.set("rewriterGradlePluginDir", rewriterGradlePluginDir);
                String rewriterPluginName = rewriterDir.getParentFile().getName();
                project.ext.set("rewriterPluginName", rewriterPluginName);
                println("rewriter---find rewriter plugin : " + rewriterPluginName);
            }
        }
        int status0 = p.waitFor();
        println("rewriter---p.waitFor(): " + status0);
        //配置rewriter插件依赖的gradle插件库
        String rewriterPluginName = project.rewriterPluginName;
        String rewriterGradlePluginDir = project.rewriterGradlePluginDir;
        dependencies {
            if (rewriterPluginName != "" && rewriterGradlePluginDir != "") {
                println("rewriter---rewriter depenencies: " + rewriterGradlePluginDir);
                // 依赖rewriter目录下的所有gradle插件相关的jar包
                classpath fileTree(dir: rewriterGradlePluginDir, include: '*.jar');
            }
        }
    }catch(Exception e){
        println("rewriter---exception: " + e.getMessage());
    }

}

try{
    //应用相应的gradle plugin
    String rewriterPluginName = project.rewriterPluginName;
    String rewriterGradlePluginDir = project.rewriterGradlePluginDir;
    if("uexNBSAppAgent".equals(rewriterPluginName)){
        apply plugin: 'newlens'
        println("rewriter---apply plugin: newlens success")
    }else if("uexOneAPM".equals(rewriterPluginName)){
        apply plugin: 'oneapm'
        println("rewriter---apply plugin: oneapm success")
    }else if("uexBonree".equals(rewriterPluginName)){
        apply plugin: 'bonree'
        println("rewriter---apply plugin: bonree success")
    }else{
        println("rewriter---no rewriter plugin or not supported plugin: " + rewriterPluginName);
    }
}catch(Exception e){
    println("rewriter---exception: " + e.getMessage());
}
repositories {
    flatDir {
        dirs 'libs'
    }
    def mavenUrl=System.getenv("GRADLE_M2_HOME");
    if(mavenUrl==null){
        println("AppCanPkgError: GRADLE_M2_HOME mavenUrl is null. Not Supported Environment.");
    }
    maven {
        url mavenUrl
    }
}

//依赖libs下的所有的aar
fileTree(dir: 'libs', include: '**/*.aar')
        .each { File file ->
    dependencies.add("compile", [name: file.name.lastIndexOf('.').with { it != -1 ? file.name[0..<it] : file.name }, ext: 'aar'])
}

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/MANIFEST.MF'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/ASL2.0'
        pickFirst 'assets/lineDashTexture.png'
    }
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs=['libs']
        }
    }
    lintOptions {
          checkReleaseBuilds false
          // Or, if you prefer, you can continue to check for errors in release builds,
          // but continue the build even when errors are found:
          abortOnError false
    }
    aaptOptions {
        cruncherEnabled = false //不检查PNG的合法性
    }
    dexOptions {
        javaMaxHeapSize "2048M"
    }

    defaultConfig {
        minSdkVersion 22
        targetSdkVersion 30
        multiDexEnabled true
        // 过滤armeabi架构，如有其它架构需要，后续可以再增加或自行定制引擎
        // 此处AbiFilters选项的值，打包服务脚本程序可能会对其进行修改，不要进行大幅度的变更格式
        ndk {
            abiFilters 'armeabi-v7a', 'arm64-v8a'
        }
    }
}
