def fetch_dir = new File(project.buildDir, 'libs')
def fetch_url = project.hasProperty('JSC_LIBS_URL') ?
        new URL(project.getProperty('JSC_LIBS_URL').toString()) :
        new URL('https://registry.npmjs.org/jsc-android/-/jsc-android-250230.2.1.tgz')
def aar_name = project.hasProperty('aar_name') ?
        project.getProperty('aar_name').toString() :
        'android-jsc-intl'

def zip_file = new File(fetch_dir, fetch_url.path.split('/').last())
def aar_file = new File(fetch_dir, "${aar_name}.aar")

def projectLibsDir = "${project.projectDir}/src/main/jni/jsc/JavaScriptCore/libs"

def downloadFile = { URL url, File dest ->
    if (!dest.getParentFile().exists()) {
        dest.getParentFile().mkdirs()
    }
    url.withInputStream { i -> dest.withOutputStream { it << i } }
}

task downloadLibs() {
    inputs.property('url', fetch_url)
    outputs.file(zip_file)
    outputs.upToDateWhen {
        zip_file.exists()
    }
    doFirst {
        if (!zip_file.exists()) {
            downloadFile(fetch_url, zip_file)
        }
    }
}

task unzipLibs(type: Copy, dependsOn: downloadLibs) {
    from tarTree(zip_file)
    into fetch_dir
    include "**/*${aar_name}*.aar"
    includeEmptyDirs false
    eachFile {
        if (it.name.endsWith('.aar')) {
            it.path = it.name
            it.name = "${aar_name}.aar"
        }
    }
    inputs.file(zip_file)
    outputs.file(aar_file)
    outputs.upToDateWhen {
        aar_file.exists()
    }
}

task pickLibs(type: Copy, dependsOn: unzipLibs) {
    from zipTree(aar_file)
    into projectLibsDir
    include 'jni/**/libjsc.so'
    includeEmptyDirs false
    eachFile {
        def path_list = new LinkedList<>(it.relativePath.segments.toList())
        path_list.removeAt(0)
        it.relativePath = new RelativePath(true, path_list[0], path_list[1])
    }
    inputs.file(zip_file)
    outputs.dir(projectLibsDir)
    outputs.upToDateWhen {
        new File(projectLibsDir).exists()
    }
}