/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

configure(rootProject) {
  task checkBrokenLinks {
    group 'Verification'
    description 'Check broken links in the entire documentation'

    dependsOn ':solr:documentation:checkBrokenLinks'
  }
}

configure(project(':solr:documentation')) {
  task checkBrokenLinks(type: CheckBrokenLinksTask, 'dependsOn': 'documentation')
  check.dependsOn checkBrokenLinks
}

@CacheableTask
class CheckBrokenLinksTask extends DefaultTask {

  // wraps input directory location in DirectoryProperty so as to lazily evaluate 'docroot' property
  // (see gradle/documentation/documentation.gradle)
  @InputDirectory
  @PathSensitive(PathSensitivity.RELATIVE)
  final DirectoryProperty docsDir = project.objects.directoryProperty()
    .fileProvider(project.providers.provider { project.docroot })

  @InputFile
  @PathSensitive(PathSensitivity.RELATIVE)
  File script = project.rootProject.file("dev-tools/scripts/checkJavadocLinks.py")

  @OutputFile
  Provider<RegularFile> outputFile = project.layout.buildDirectory.file('check-broken-links-output.txt')

  @TaskAction
  def check() {
    def result
    outputFile.get().asFile.withOutputStream { output ->
      result = project.exec {
        executable project.externalTool("python3")
        ignoreExitValue = true
        standardOutput = output
        errorOutput = output
        args = [
          "-B",
          script.absolutePath,
          docsDir.get().getAsFile()
        ]
      }
    }

    if (result.getExitValue() != 0) {
      throw new GradleException("Broken links check failed. Command output at: ${outputFile.get()}")
    }
  }
}
