allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

val newBuildDir: Directory =
    rootProject.layout.buildDirectory
        .dir("../../build")
        .get()
rootProject.layout.buildDirectory.value(newBuildDir)

subprojects {
    val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
    project.layout.buildDirectory.value(newSubprojectBuildDir)
}
subprojects {
    if (project.name == "agora_rtc_engine" || project.name == "iris_method_channel") {
        tasks.configureEach {
            if (name.startsWith("configureCMake") || name.startsWith("buildCMake")) {
                doFirst {
                    val cmakeFile = listOf(
                        project.file("src/main/cpp/CMakeLists.txt"),
                        project.file("../src/CMakeLists.txt"),
                    ).firstOrNull { it.exists() }

                    if (cmakeFile != null) {
                        val text = cmakeFile.readText()
                        if (!text.contains("c++_shared")) {
                            val patchedText =
                                if (text.contains("target_link_libraries")) {
                                    text.replace(
                                        "        EGL\n        )",
                                        "        EGL\n        c++_shared\n        )",
                                    )
                                } else {
                                    text + """

target_link_libraries(${'$'}{LIBRARY_NAME}
        PRIVATE
        c++_shared
        )
"""
                                }
                            cmakeFile.writeText(patchedText)
                        }
                    }
                }
            }
        }
    }
}
subprojects {
    project.evaluationDependsOn(":app")
}

tasks.register<Delete>("clean") {
    delete(rootProject.layout.buildDirectory)
}
