/*
 * Copyright (c) 2025 Meshtastic LLC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

def getMeshProperty(String key) {
    def env = System.getenv(key)
    if (env) return env

    def currentDir = settingsDir
    while (currentDir != null) {
        def localFile = new File(currentDir, "local.properties")
        if (localFile.exists()) {
            def props = new Properties()
            localFile.withInputStream { props.load(it) }
            if (props.containsKey(key)) return props.getProperty(key)
        }
        def configFile = new File(currentDir, "config.properties")
        if (configFile.exists()) {
            def props = new Properties()
            configFile.withInputStream { props.load(it) }
            if (props.containsKey(key)) return props.getProperty(key)
        }
        currentDir = currentDir.parentFile
    }
    return null
}

buildCache {
    local {
        enabled = true
    }
    remote(HttpBuildCache) {
        // Some servers have issues with Expect: 100-continue and return 403.
        useExpectContinue = false
        def cacheUrl = getMeshProperty("GRADLE_CACHE_URL")?.trim()
        def cacheUsername = getMeshProperty("GRADLE_CACHE_USERNAME")?.trim()
        def cachePassword = getMeshProperty("GRADLE_CACHE_PASSWORD")?.trim()

        if (cacheUrl) {
            def isLogic = settingsDir.name == "build-logic"
            logger.lifecycle "Meshtastic ${isLogic ? 'Build Logic' : 'Build'}: Remote cache URL found."

            // Ensure trailing slash for cache servers
            url = cacheUrl.endsWith("/") ? cacheUrl : "${cacheUrl}/"

            if (cacheUsername && cachePassword) {
                credentials {
                    username = cacheUsername
                    password = cachePassword
                }
            }

            allowInsecureProtocol = true
            allowUntrustedServer = true

            // Keep push enabled if credentials are provided.
            // This naturally disables push for fork PRs which don't have access to secrets.
            push = (cacheUsername && cachePassword)

            enabled = true
        } else {
            enabled = false
        }
    }
}
