
def backupOriginalFile(){
    //在此写上占用的文件，路径就填相对当前项目的相对路径即可，以此尝试解决windows电脑文件占用的问题
    deleteOnSave("/test-lib/build/intermediates/runtime_library_classes_jar/debug/classes.jar")
    deleteOnSave("/test-lib/build/intermediates/compile_library_classes_jar/debug/classes.jar")
}


android.applicationVariants.configureEach {
    def variantName = name
    tasks.matching { it.name.endsWith("AssembleAndroidAopTask") && it.name.contains(variantName) }.configureEach {
        doFirst {
            if (System.getProperty("os.name").toLowerCase().contains("win")) {
                println("Before AOP for variant $variantName")
                restoreOriginalFile()
            }
        }
        doLast {
            if (System.getProperty("os.name").toLowerCase().contains("win")) {
                println("After AOP for variant $variantName")
                backupOriginalFile()
            }
        }
    }
}

def deleteOnSave(String deleteFilePath){
    File targetFile = new File(project.rootProject.buildDir.absolutePath+File.separator+"deleteCache",deleteFilePath)
    File deleteFile = new File(project.rootProject.buildDir.parentFile.absolutePath,deleteFilePath.replace(project.rootProject.buildDir.parentFile.absolutePath,""))
    copyFile(deleteFile,targetFile)
    deleteFile.delete()
}

def copyFile(File sourceFile,File targetFile){
    if (!sourceFile.exists()){
        return
    }
    targetFile.parentFile.mkdirs()
    sourceFile.withInputStream { input ->
        targetFile.withOutputStream { output ->
            output << input
        }
    }

//    println "Copied ${sourceFile} to ${targetFile}"
}

def restoreOriginalFile(){
    def rootDir = file(project.rootProject.buildDir.absolutePath+File.separator+"deleteCache")
    if (!rootDir.exists()){
        return
    }

    def allFiles = []
    rootDir.eachFileRecurse { file ->
        if (file.isFile()) {
            allFiles << file
        }
    }


    def count = 0
    for (final File file in allFiles) {
        File sourceFile = new File(project.rootProject.buildDir.parentFile.absolutePath,file.getAbsolutePath().replace(rootDir.getAbsolutePath(),""))
        if (!sourceFile.exists()){
            copyFile(file,sourceFile)
            count++
        }
        file.delete()
    }

    println "恢复了 ${count} 个备份文件："
    if (rootDir.exists()) {
        rootDir.deleteDir()
    }
}

//测试使用
task aaTestDelete() {
    doLast {
        backupOriginalFile()
    }
}
//测试使用
task aaTestRestore() {
    doLast {
        restoreOriginalFile()
    }
}