import org.gradle.util.GradleVersion

// Only run when dependency graph is explicitly enabled
if (System.env.GITHUB_DEPENDENCY_GRAPH_ENABLED != "true") {
  return
}

// Do not run for unsupported versions of Gradle
if (GradleVersion.current().baseVersion < GradleVersion.version("5.0")) {
  println "::warning::Dependency Graph is not supported for Gradle versions < 5.0. No dependency snapshot will be generated."
  return
}

// Attempt to find a unique job correlator to use based on the environment variable
// This is only required for top-level builds
def isTopLevelBuild = gradle.getParent() == null
if (isTopLevelBuild) {
  def reportFile = getUniqueReportFile(System.env.GITHUB_JOB_CORRELATOR)

  if (reportFile == null) {
    println "::warning::No dependency snapshot generated for step. Could not determine unique job correlator - specify GITHUB_JOB_CORRELATOR var for this step."
    return
  }

  def githubOutput = System.getenv("GITHUB_OUTPUT")
  if (githubOutput) {
      new File(githubOutput) << "dependency-graph-file=${reportFile.absolutePath}\n"
  }


  println "Generating dependency graph into '${reportFile}'"
}

apply from: 'github-dependency-graph-gradle-plugin-apply.groovy'

/**
 * Using the supplied jobCorrelator value:
 * - Checks if report file already exists
 * - If so, tries to find a unique value that does not yet have a corresponding report file.
 * - When found, this value is set as a System property override.
 */
File getUniqueReportFile(String jobCorrelator) {
    def reportDir = System.env.DEPENDENCY_GRAPH_REPORT_DIR
    def reportFile = new File(reportDir, jobCorrelator + ".json")
    if (!reportFile.exists()) return reportFile

    // Try at most 100 suffixes
    for (int i = 1; i < 100; i++) {
        def candidateCorrelator = jobCorrelator + "-" + i
        def candidateFile = new File(reportDir, candidateCorrelator + ".json")
        if (!candidateFile.exists()) {
           System.properties['GITHUB_JOB_CORRELATOR'] = candidateCorrelator
           return candidateFile
        }
    }

    // Could not determine unique job correlator
    return null
}
