/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java Library project to get you started.
 * For more details take a look at the Java Libraries chapter in the Gradle
 * User Manual available at https://docs.gradle.org/5.6.2/userguide/java_library_plugin.html
 */

import com.appland.tasks.ShadowRelocation

plugins {
  id 'jacoco'
  id 'signing'
}

repositories {
  jcenter()
  mavenCentral()
}

// hardcoded -- could be redefined via env variables and project properties (see below)
def parameterizedVersion = findProperty('appMapAgentVersion')
def travisVersion = System.getenv("TRAVIS_BRANCH")

def versionLikeRegexp = /^\d+\.\d+.*/
def travisVersionValid = travisVersion && (travisVersion ==~ versionLikeRegexp)

def defaultGitSlug = "applandinc/appmap-java"
def currentGitSlug = System.getenv("TRAVIS_REPO_SLUG") ?: defaultGitSlug

def defaultGroupId      = 'com.appland'
def defaultArtifactId   = 'appmap-agent'
def publishGroupId      = findProperty('publishGroupId') ?: defaultGroupId
def publishArtifactId   = findProperty('publishArtifactId') ?: defaultArtifactId

def defaultDescription = "Inspect and record the execution of Java for use with App Land"
def parameterizedDescription = findProperty('appMapAgentDescription') ?: defaultDescription


// these two are required by Gradle-Nexus-Publishing
version = parameterizedVersion ?: ( travisVersionValid ? travisVersion : defaultVersion )
group = publishGroupId

final tinylogVersion = '2.6.2'

final javassistVersion = '3.29.2-GA'
dependencies {
  implementation project(':runtime')

  // Note that implementation dependencies added here will have their packages
  // rewritten by Shadow (unless they're explicitly excluded below). As a
  // result, you won't be able to add hooks for anything in those packages.
  implementation 'com.alibaba:fastjson:1.2.83'
  implementation "org.javassist:javassist:${javassistVersion}"
  implementation 'org.reflections:reflections:0.9.11'
  implementation 'net.bytebuddy:byte-buddy:1.14.10'
  implementation 'org.apache.commons:commons-lang3:3.10'
  implementation 'commons-io:commons-io:2.15.1'
  implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.13.2'
  implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.4.2'
  implementation 'org.slf4j:slf4j-nop:1.7.30'
  implementation 'info.picocli:picocli:4.6.1'
  implementation 'org.apache.httpcomponents:httpcore-nio:4.4.15'
  implementation 'org.eclipse.jgit:org.eclipse.jgit:5.13.3.202401111512-r'

  implementation "org.tinylog:tinylog-api:${tinylogVersion}"
  implementation "org.tinylog:tinylog-impl:${tinylogVersion}"

  // We have to refer to annotations by name (for example, see CodeObject), so
  // there's no need for a compile-time dependency on
  // com.appland.appmap.annotation.
  // implementation project(':annotation')

  testImplementation platform('org.junit:junit-bom:5.8.2')
  testImplementation 'org.junit.jupiter:junit-jupiter'
  testImplementation 'org.junit.jupiter:junit-jupiter-params'
  testImplementation 'org.junit.vintage:junit-vintage-engine'

  testImplementation 'com.github.stefanbirkner:system-rules:1.19.0'
  testImplementation 'com.github.stefanbirkner:system-lambda:1.2.1'
  testImplementation "org.mockito:mockito-core:[3.4,4)"
  testImplementation 'com.github.marschall:memoryfilesystem:2.6.1'

  testImplementation 'org.apache.maven:maven-model:3.9.5'
}

compileJava {
    sourceCompatibility = '1.8'
    targetCompatibility = '1.8'
}

jar {
  manifest {
    attributes 'Premain-Class': 'com.appland.appmap.Agent'
    attributes 'Main-Class': 'com.appland.appmap.cli.CLI'
    attributes 'Implementation-Version': version
  }
}

apply plugin: 'com.github.johnrengelman.shadow'

shadowJar {
  baseName = 'appmap'
  classifier = ''
  minimize() {
    // tinylog computes the dependencies it needs at runtime, so don't exclude
    // anything.
    exclude(dependency('org.tinylog:.*:.*'))
  }

  dependsOn ':runtime:jar'
  from(project(':runtime').tasks.named('jar').get().destinationDirectory) {
  // Per
  // https://imperceptiblethoughts.com/shadow/configuration/dependencies/#embedding-jar-files-inside-your-shadow-jar,
  // we need to rename the runtime jar to get it embedded in the output jar.
  // We'll rename it when we extract it.
    include '*.jar'
    rename '(.+).jar', '$1.zip'
  }

  dependencies {
    exclude(dependency('org.apache.httpcomponents:.*:.*'))
    exclude(project(':runtime'))
 }
}

sourceSets {
  main {
    java {
      // Eclipse JDT Language Server (used by VS Code's Language Support for
      // Java extension), doesn't understand Gradle plugins, per
      // https://github.com/eclipse/buildship/issues/1126#issuecomment-1004643907
      // . Adding it here allows the extension to work, and doesn't seem to
      // impact anything else.
      srcDirs = ['src/main/java', 'buildSrc/src/main/groovy']
    }
  }

  test {
    java {
      srcDirs = ['src/test/java']
    }
  }
}

task integrationTest(type: Test) {
  description = 'Runs integration tests'
  group = 'verification'

  include 'com/appland/appmap/integration/**'

  dependsOn shadowJar
  maxParallelForks = 1
  jvmArgs "-javaagent:${shadowJar.archiveFile.get()}"
  systemProperty "appmap.config.file", "$projectDir/appmap.yml"
  // systemProperty "appmap.log.level", "debug"
}

test {
  useJUnitPlatform()
  dependsOn shadowJar
  dependsOn cleanTest
  exclude 'com/appland/appmap/integration/**'
  // systemProperty "appmap.log.level", "debug"
}

task relocateShadowJar(type: ShadowRelocation) {

  target = tasks.shadowJar
  prefix = "com.appland.shade"
  excludes = [
    "java.",
    "org.apache.http",
    "com.appland.appmap.runtime"
  ]
}

tasks.shadowJar.dependsOn tasks.relocateShadowJar

jacocoTestReport {
  reports {
    xml.enabled false
    csv.enabled false
    html.enabled true
  }
}

// extra artifacts used in publishing
task sourcesJar(type: Jar) {
  from sourceSets.main.allJava
  classifier = 'sources'
}

// for some reason this block generates empty Javadoc
// which we use as a workaround to bypass javadoc errors issue
javadoc {
  exclude 'com/appland/**'
}

task mockJavadocJar(type: Jar) {
  classifier = 'javadoc'
  from javadoc.destinationDir
}

apply plugin: 'maven-publish'
publishing {
  publications {

    appMapAgent(MavenPublication) {

      // requirements: https://central.sonatype.org/pages/requirements.html

      // 1. coordinates (parameterized)

      groupId publishGroupId
      artifactId publishArtifactId

      // version defined globally

      // 2. artifacts
      // inclusion of javadoc and source jars is Maven-Central requirement

      artifact shadowJar
      artifact sourcesJar
      artifact mockJavadocJar // empty javadoc generated until errors are fixed

      //// the artifacts below added automatically by `java { with... }` block above
      // artifact sourcesJar
      // artifact javadocJar

      // metadata
      // TBD: parameterize more values?

      pom {
        name = "$publishGroupId:$publishArtifactId"
        description = "Inspect and record the execution of Java for use with App Land"
        url = "https://appland.com"

        licenses {
          license {
            name = "MIT"
            url = "https://raw.githubusercontent.com/$currentGitSlug/master/LICENSE.txt"
          }
        }
        developers {
          developer {
            // id = "kgilpin"
            name = "Kevin Gilpin"
            email = "kevin@appland.com"
            organization = "AppLand Inc."
            url = "https://dev.to/kgilpin"
          }
        }
        scm {
          connection = "scm:git:git://github.com/${currentGitSlug}.git"
          developerConnection = "scm:git:ssh://github.com:${currentGitSlug}.git"
          url = "https://github.com/${currentGitSlug}/tree/master"
        }
      }
    }
  }
}

if (project.hasProperty("signingKey")) {
  apply plugin: 'signing'
  signing {
    def signingKey = findProperty("signingKey")
    def signingPassword = findProperty("signingPassword")
    useInMemoryPgpKeys(signingKey, signingPassword)
    sign publishing.publications.appMapAgent
  }
}

tasks.publishToMavenLocal.dependsOn(check, integrationTest)