def fetch_dir = new File(project.buildDir, 'libs')
def fetch_url = project.hasProperty('QuickJS_LIBS_URL') ?
        new URL(project.getProperty('QuickJS_LIBS_URL').toString()) :
        new URL('https://github.com/OrangeLab/Hummer-Virtual-JS-Engine/releases/download/2.1.6/napi_qjs_column_v2.1.6.tar.gz')

def zip_file = new File(fetch_dir, fetch_url.path.split('/').last())

def projectLibsDir = "${project.projectDir}/src/main/jni/napi/napi"

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 pickLibs(type: Copy, dependsOn: downloadLibs) {
    from tarTree(zip_file)
    into projectLibsDir
    include '**/libs/**/libqjs.so', '**/include/**'
    includeEmptyDirs false
    eachFile {
        def path_list = new LinkedList<>(it.relativePath.segments.toList())
        path_list.remove(0)
        if (it.path.startsWith("./libs/")) {
            path_list.add(1, "qjs")
        }
        it.relativePath = new RelativePath(true, path_list.toArray(new String[0]))
    }
    inputs.file(zip_file)
    outputs.dir(projectLibsDir)
    outputs.upToDateWhen {
        new File(projectLibsDir).exists()
    }
}