import smali.SmaliTask

tasks.whenTaskAdded { task ->
    def name = task.name
    if (name.startsWith('preShade') && name.endsWith('Build')) {
        task.dependsOn 'buildShadeSmali'
    }
}

dependencies {
    shadeImplementation fileTree(dir: 'build/shadelibs', include: '*.jar')
}

task 'buildShadeSmali' {
    def smaliInputDir = file('shade/smali')
    def dexOutputDir = file('build/shadesmali')
    def jarOutputDir = file('build/shadelibs')

    smaliInputDir.mkdirs()
    dexOutputDir.mkdirs()
    jarOutputDir.mkdirs()

    smaliInputDir.eachDirRecurse() { dir ->
        def smaliFiles = fileTree(dir: dir, include: '*.smali')
        if (!smaliFiles.empty) {
            def relativeDir = smaliInputDir.toPath().relativize(dir.toPath())
            def name = relativeDir.toString().replace('/', '_').replace('\\', '_')

            def intermediateFile = dexOutputDir.toPath().resolve("${name}.dex").toFile()
            def jarFile = jarOutputDir.toPath().resolve("${name}.jar").toFile()
            def errorFile = jarOutputDir.toPath().resolve("${name}-error.zip").toFile()

            dependsOn "dex_to_jar_${name}"
            task "smali_to_dex_${name}"(type: SmaliTask) {
                source = smaliFiles
                destination = intermediateFile
            }
            task "dex_to_jar_${name}"(type: JavaExec) {
                dependsOn "smali_to_dex_${name}"
                classpath = fileTree(dir: file('buildSrc/dex2jar'), include: '*.jar')
                main = "com.googlecode.dex2jar.tools.Dex2jarCmd"
                args = [
                        intermediateFile,
                        "--output", jarFile,
                        "--exception-file", errorFile,
                        "--not-handle-exception",
                        "--force"
                ]

                // Up-to-date checks
                inputs.file intermediateFile
                outputs.file jarFile
            }
        }
    }
}
