/*
 * 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
}

develocity {
    buildScan {
        capture {
            fileFingerprints = true
        }
        // Publish scans in CI for build failure debugging and performance profiling.
        // Uses scans.gradle.com free tier (public scans). Disabled locally.
        def isCi = System.getenv("CI") != null
        publishing.onlyIf { isCi }
        uploadInBackground = !isCi
        termsOfUseUrl = "https://gradle.com/help/legal-terms-of-use"
        termsOfUseAgree = "yes"
    }
    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 Develocity/GE 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
            }
        }
    }
}
