import org.apache.tools.ant.filters.FixCrLfFilter
import org.gradle.internal.os.OperatingSystem

apply plugin: 'com.android.library'

// Values set here will be overriden by AppVeyor, feel free to modify during development.
def buildVersionName = 'v0.4.6.2'
def buildVersionCode = 233

if (System.env.APPVEYOR_BUILD_VERSION != null) {
    buildVersionName = "v${System.getenv('appveyor_build_version')}"
}

if (System.env.APPVEYOR_BUILD_NUMBER != null) {
    // Split is necessary because PRs set the build number to "1234-something".
    def parts = System.env.APPVEYOR_BUILD_NUMBER.split('-')
    buildVersionCode = Integer.valueOf(parts[0])
}

version buildVersionName

ext {
    versionCode = buildVersionCode
    module_name = "EdXposed"
    jar_dest_dir = "${projectDir}/template_override/system/framework/"
    is_windows = OperatingSystem.current().isWindows()
    backends = ["YAHFA", "SandHook", "Whale"]
    yahfa_module_id = "riru_edxposed"
    sandhook_module_id = yahfa_module_id + "_sandhook"
    whale_module_id = yahfa_module_id + "_whale"
    yahfa_authors = "solohsu, MlgmXyysd & rk700"
    sandhook_authors = "solohsu, MlgmXyysd & ganyao114"
    whale_authors = "solohsu, MlgmXyysd & asLody"

    riruModuleId = "edxp"
    zipPathMagiskRelease = "$buildDir/tmp/release/magisk"
}

android {
    compileSdkVersion 28
    defaultConfig {
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion

        externalNativeBuild {
            cmake {
                abiFilters 'arm64-v8a', 'armeabi-v7a', 'x86', 'x86_64'
                cppFlags "-std=c++17 -ffixed-x18 -Qunused-arguments -frtti"
                cFlags "-std=gnu99 -ffixed-x18 -Qunused-arguments -frtti"
            }
        }
    }

    buildTypes {
        debug {
            externalNativeBuild {
                cmake {
                    cppFlags "-O0"
                    cFlags "-O0"
                }
            }
        }
        release {
            externalNativeBuild {
                cmake {
                    cppFlags "-fvisibility=hidden -fvisibility-inlines-hidden -O2 -s -Wno-unused-value"
                    cFlags "-fvisibility=hidden -fvisibility-inlines-hidden -O2 -s -Wno-unused-value"
                }
            }
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "src/main/cpp/CMakeLists.txt"
        }
    }
}

task copyDalvikdxJar {
    def jarTask = tasks.getByPath(':dalvikdx:dexInJar')
    dependsOn jarTask
    doLast {
        copy {
            from jarTask
            into jar_dest_dir
        }
    }
    onlyIf {
        !jarTask.state.upToDate || !file(jar_dest_dir + jarTask.archiveName).exists()
    }
}

task copyDexmakerJar {
    def jarTask = tasks.getByPath(':dexmaker:dexInJar')
    dependsOn jarTask
    doLast {
        copy {
            from jarTask
            into jar_dest_dir
        }
    }
    onlyIf {
        !jarTask.state.upToDate || !file(jar_dest_dir + jarTask.archiveName).exists()
    }
}

task cleanTemplate(type: Delete) {
    delete file(templateSystemx86Path)
}

afterEvaluate {

    android.libraryVariants.all { variant ->

        def variantCapped = variant.name.capitalize()
        def variantLowered = variant.name.toLowerCase()

        backends.each { backend ->

            def backendLowered = backend.toLowerCase()
            def backendCapped = backendLowered.capitalize()
            def authorList = property("${backendLowered}" + "_authors")
            def magiskModuleId = property("${backendLowered}" + "_module_id")

            def prepareJarsTask = task("prepareJars${backendCapped}${variantCapped}") {
                dependsOn cleanTemplate, copyDalvikdxJar, copyDexmakerJar
                dependsOn tasks.getByPath(":edxp-${backendLowered}:makeAndCopy${variantCapped}")
            }

            def prepareMagiskFilesTask = task("prepareMagiskFiles${backendCapped}${variantCapped}", type: Delete) {
                dependsOn prepareJarsTask, "assemble${variantCapped}"
                delete file(zipPathMagiskRelease)
                doFirst {
                    copy {
                        from "${projectDir}/tpl/edconfig.tpl"
                        into templateFrameworkPath
                        rename "edconfig.tpl", "edconfig.jar"
                        expand(version: "$version", backend: "$backend")
                    }
                    copy {
                        from "${projectDir}/tpl/module.prop.tpl"
                        into templateRootPath
                        rename "module.prop.tpl", "module.prop"
                        expand(moduleId: "$magiskModuleId", backend: "$backendCapped",
                                versionName: "$version" + " ($backend)",
                                versionCode: "$versionCode", authorList: "$authorList")
                        filter(FixCrLfFilter.class, eol: FixCrLfFilter.CrLf.newInstance("lf"))
                    }
                }
                def libPathRelease = "${buildDir}/intermediates/cmake/${variantLowered}/obj"
                doLast {
                    copy {
                        from "${projectDir}/template_override"
                        into zipPathMagiskRelease
                    }
//                    copy {
//                        from "${projectDir}/template_override/util_functions.sh"
//                        into "${zipPathMagiskRelease}/"
//                        filter { line -> line
//                                .replaceAll('%VERSION%', "$version")
//                                    .replaceAll('%VERSION_CODE%', "$versionCode")
//                                .replaceAll('%BACKEND%', "$backendCapped") }
//                        filter(FixCrLfFilter.class, eol: FixCrLfFilter.CrLf.newInstance("lf"))
//                    }
                    copy {
                        from "$libPathRelease/armeabi-v7a"
                        into "$zipPathMagiskRelease/system/lib"
                    }
                    copy {
                        from "$libPathRelease/arm64-v8a"
                        into "$zipPathMagiskRelease/system/lib64"
                    }
                    copy {
                        from "$libPathRelease/x86"
                        into "$zipPathMagiskRelease/system_x86/lib"
                    }
                    copy {
                        from "$libPathRelease/x86_64"
                        into "$zipPathMagiskRelease/system_x86/lib64"
                    }
                }
            }

            def zipTask = task("zip${backendCapped}${variantCapped}", type: Zip) {
                dependsOn prepareMagiskFilesTask
                archiveName "${module_name}-${backend}-${project.version}-${variantLowered}.zip"
                destinationDir file("$projectDir/release")
                from "$zipPathMagiskRelease"
            }

            task("push${backendCapped}${variantCapped}", type: Exec) {
                dependsOn zipTask
                workingDir "${projectDir}/release"
                def commands = ["adb", "push",
                                "${module_name}-${backend}-${project.version}-${variantLowered}.zip",
                                "/sdcard/"]
                if (is_windows) {
                    commandLine 'cmd', '/c', commands.join(" ")
                } else {
                    commandLine commands
                }
            }
        }

        // backward compatible
        task("zip${variantCapped}") {
            dependsOn "zipYahfa${variantCapped}"
        }
        task("push${variantCapped}") {
            dependsOn "pushYahfa${variantCapped}"
        }
    }

}