// Build Script
// ------------

buildscript {
  repositories {
    mavenLocal()
    mavenCentral()
  }
  dependencies {
    classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.5'
  }
}

apply plugin: "java"
apply plugin: "maven"
apply plugin: "signing"
apply plugin: "idea"
apply plugin: "eclipse"
apply plugin: "com.google.protobuf"
apply plugin: "application"

sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8

group = "com.google.api"
version = "0.0.9-SNAPSHOT"
archivesBaseName = "api-compiler"
mainClassName = "com.google.api.tools.framework.tools.configgen.ServiceConfigGeneratorTool"

task javadocJar(type: Jar) {
    classifier = 'javadoc'
    from javadoc
}

// Dependencies
// ------------

ext {
  // Shortcuts for libraries we are using
  libraries = [
      // General
      guava: 'com.google.guava:guava:26.0-jre',
      jsr305: 'com.google.code.findbugs:jsr305:3.0.0',
      autovalue: 'com.google.auto.value:auto-value:1.6',
      autovalueAnnotations: 'com.google.auto.value:auto-value-annotations:1.6.2',
      cglib: 'cglib:cglib:3.1',
      guice: 'com.google.inject:guice:4.0',
      commonsLang: 'org.apache.commons:commons-lang3:3.6',
      snakeyaml: 'org.yaml:snakeyaml:1.18',
      swaggerModel: 'io.swagger:swagger-models:1.5.9',
      swaggerParser: 'io.swagger:swagger-parser:1.0.22',
      grpcCore: 'com.google.api.grpc:grpc-google-common-protos:1.12.0',
      apacheCommonCli: 'commons-cli:commons-cli:1.4',
      jsonSchemaValidator: 'com.github.fge:json-schema-validator:2.0.0',

      // Testing
      junit: 'junit:junit:4.12',
      mockito: 'org.mockito:mockito-core:2.21.0',
      truth: 'com.google.truth:truth:0.42',
      jodaTime: 'joda-time:joda-time:2.9',

      // Protobuf
      protobuf: 'com.google.protobuf:protobuf-java:3.7.1',
      protobufUtil: 'com.google.protobuf:protobuf-java-util:3.7.1',
      protoc:  'com.google.protobuf:protoc:3.7.1'
  ]
}

repositories {
  mavenLocal()
  mavenCentral()
}

dependencies {
  compile libraries.guava,
    libraries.jsr305,
    libraries.autovalue,
    libraries.autovalueAnnotations,
    libraries.protobuf,
    libraries.protobufUtil,
    libraries.cglib,
    libraries.swaggerModel,
    libraries.swaggerParser,
    libraries.guice,
    libraries.commonsLang,
    libraries.snakeyaml,
    libraries.jsonSchemaValidator,
    libraries.grpcCore,
    libraries.apacheCommonCli

  testCompile libraries.junit,
    libraries.mockito,
    libraries.truth,
    libraries.jodaTime
}

run {
  if ( project.hasProperty("appArgs") ) {
    args Eval.me(appArgs)
  }
}

// Test data
// ---------

sourceSets {
  test {
    resources {
      // Include all resources from testdata folders.
      srcDir 'src/test/java'
      include '**/testdata/*'
    }
    resources {
      // Include protos of core platform as some tests depend on this.
      srcDir "${projectDir}/modules/googleapis"
      include '**/*.proto'
    }
  }
}

// Test Logging
// ------------

test {
  testLogging {
      events "passed", "skipped", "failed", "standardOut", "standardError"
  }
}

// Protobuf
// --------

protobuf {
  protoc {
    artifact = libraries.protoc
  }
}

sourceSets {
  main {
    proto {
      // Include proto sources for testing.
      srcDir "${projectDir}/src/test/java/com/google/api/tools/framework/yaml/testdata"
    }
    java {
      // Include location where proto plugin puts generated sources.
      srcDir "${buildDir}/generated/source/proto/test/java"
    }
  }
}

// Making test utilities available for other projects
// --------------------------------------------------

task testJar(type: Jar, dependsOn: testClasses) {
  classifier = 'testing'
  from sourceSets.test.output
}

configurations {
  testing
  published.extendsFrom testing, archives
}

artifacts {
  testing testJar
}

install {
  configuration = configurations.published
}

// Source jar
// ----------

task sourcesJar(type: Jar, dependsOn: classes) {
  classifier = 'sources'
  from sourceSets.main.allSource,
       sourceSets.test.allSource
}

artifacts {
  archives javadocJar, sourcesJar, testJar
}

// Jar with dependencies
// ---------------------
task buildApplication(type: Jar) {
  baseName = archivesBaseName + '-with-deps'
  from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
  with jar
  manifest {
    attributes 'Main-Class': 'com.google.api.tools.framework.tools.configgen.ServiceConfigGeneratorTool'
  }
}

// Eclipse Annotation Processing
// -----------------------------

// TODO(wrwg): figure whether there is direct support for this in eclipse plugin,
// and use that instead.

ext {
  eclipseAptFolder = '.apt_generated'
  eclipseSettingsDir = file('.settings')
}

configurations {
  codeGeneration
}

dependencies {
  codeGeneration libraries.autovalue, libraries.jsr305
  compile libraries.autovalue, libraries.jsr305
}

compileJava.classpath += configurations.codeGeneration

eclipse {
  jdt.file.withProperties {
    it['org.eclipse.jdt.core.compiler.processAnnotations'] = 'enabled'
  }
}

tasks.eclipseJdt {
  doFirst {
    def aptPrefs =
        file("${eclipseSettingsDir}/org.eclipse.jdt.apt.core.prefs")
    aptPrefs.parentFile.mkdirs()

    aptPrefs.text = """\
        eclipse.preferences.version=1
        org.eclipse.jdt.apt.aptEnabled=true
        org.eclipse.jdt.apt.genSrcDir=${eclipseAptFolder}
        org.eclipse.jdt.apt.reconcileEnabled=true
        """.stripIndent()

    file('.factorypath').withWriter {
      new groovy.xml.MarkupBuilder(it).'factorypath' {
        project.configurations.codeGeneration.each { dep->
          factorypathentry(
              kind:'EXTJAR',
              id:dep.absolutePath,
              enabled:true,
              runInBatchMode:false)
        }
      }
    }
  }
}

tasks.cleanEclipseJdt {
  doFirst {
    delete file("${eclipseSettingsDir}/org.eclipse.jdt.apt.core.prefs"),
    file('.factorypath')
  }
}

signing {
  required { gradle.taskGraph.hasTask("uploadArchives") }
  sign configurations.archives
}

if (JavaVersion.current().isJava8Compatible()) {
    allprojects {
        tasks.withType(Javadoc) {
            // disable the crazy super-strict doclint tool
            options.addStringOption('Xdoclint:none', '-quiet')
        }
    }
}

if (project.hasProperty('ossrhUsername') && project.hasProperty('ossrhPassword')) {
  uploadArchives {
    repositories {
      mavenDeployer {

        beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }

        repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
          authentication(userName: ossrhUsername, password: ossrhPassword)
        }

        snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") {
          authentication(userName: ossrhUsername, password: ossrhPassword)
        }

        pom.project {
          name 'Google API Compiler'
          packaging 'jar'
          artifactId 'api-compiler'
          description 'Google API Compiler.'
          url 'https://github.com/googleapis/api-compiler'

          scm {
            url 'https://github.com/googleapis/api-compiler'
            connection 'scm:git:https://github.com/googleapis/api-compiler.git'
          }

          licenses {
            license {
              name 'The Apache License, Version 2.0'
              url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
            }
          }

          developers {
            developer {
              id 'GoogleAPIs'
              name 'GoogleAPIs'
              email 'googleapis@googlegroups.com'
              url 'https://github.com/googleapis'
              organization 'Google, Inc.'
              organizationUrl 'https://www.google.com'
            }
          }
        }
      }
    }
  }
} else {
  logger.warn("The uploadArchives task was skipped. The ossrhUsername "
    + "and ossrhPassword properties need to be set correctly in "
    + "your ~/.gradle/gradle.properties file in order to upload archives.")
}

