/*
 * Copyright Thoughtworks, Inc.
 *
 * Licensed 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.
 */

import com.thoughtworks.go.build.DownloadFile
import com.thoughtworks.go.build.TextUtils
import com.thoughtworks.go.build.VerifyJarTask

description = 'GoCD TFS SDK wrapper v14'

jar {
  archiveClassifier = 'classes'
}

def destFile(String url) {
  new File(gradle.gradleUserHomeDir, "download-cache/${TextUtils.md5Hex(url)}/${new File(URI.create(url).toURL().path).name}")
}

tasks.register('downloadTfsSdk', DownloadFile) {
  def srcUrl = "https://github.com/microsoft/team-explorer-everywhere/releases/download/${project.versions.tfsSdk}/TFS-SDK-${project.versions.tfsSdk}.zip"
  src srcUrl
  dest destFile(srcUrl)
  checksum = project.versions.tfsSdkSha256sum
}

tasks.register('extractTfsSdk', Copy) {
  dependsOn downloadTfsSdk
  def sdk = downloadTfsSdk.outputs.files.singleFile
  def sdkTarget = layout.buildDirectory.dir("tfssdk")
  inputs.file(sdk)
  outputs.dir(sdkTarget)

  doFirst {
    delete sdkTarget
  }

  from(project.zipTree(sdk)) {
    include "*/redist/**"
    eachFile { FileCopyDetails fcd ->
      fcd.relativePath = new RelativePath(true, fcd.relativePath.segments.drop(2))
    }
    includeEmptyDirs = false
  }
  into sdkTarget
}

dependencies {
  implementation project(':base')
  implementation project(':common')
  implementation project(':domain')
  implementation files(tasks.named('extractTfsSdk').map { Copy copy -> new File(copy.destinationDir, "lib/com.microsoft.tfs.sdk-${project.versions.tfsSdk}.jar") })
  compileOnly project.deps.jetBrainsAnnotations

  testImplementation project.deps.junit5Api
  testRuntimeOnly project.deps.junit5Engine
  testRuntimeOnly project.deps.junit5PlatformLauncher
  testImplementation project.deps.mockitoCore
  testImplementation project.deps.assertJ
}

def fatJar = tasks.register('fatJar', Jar) {
  finalizedBy 'verifyJar'
  dependsOn extractTfsSdk, jar
  def processedSdk = extractTfsSdk.outputs.files.singleFile
  inputs.dir(processedSdk)

  from(jar.archiveFile) { into('lib/') }

  from("${processedSdk}/lib") {
    include "*.jar"
    into 'lib/'
  }
  from("${extractTfsSdk.outputs.files.singleFile}/native") {
    into 'tfssdk/native'
  }
}

tasks.register('verifyJar', VerifyJarTask) {
  jarTask = fatJar
  expectedJars = [
    "lib": [
      "tfs-impl-14-${project.version}-classes.jar",
      "com.microsoft.tfs.sdk-${project.versions.tfsSdk}.jar",
    ]
  ]
}

artifacts {
  fatJarConfig fatJar
}
