buildscript {
  repositories {
    google()
    jcenter()
    mavenCentral()
    maven { url 'https://jitpack.io' }
  }

  dependencies {
    classpath Deps.tools_android_gradle_plugin
    classpath Deps.tools_bintray_gradle_plugin
    classpath Deps.tools_kotlin_gradle_plugin
    classpath Deps.androidx_benchmark_gradle_plugin
  }
}

def gradleBuildDir = System.getenv('GRADLE_BUILD_DIR')
if (gradleBuildDir != null) {
  println "[Configuration] Building project in ${gradleBuildDir}"
  allprojects {
    buildDir = "${gradleBuildDir}/${project.name}"
  }
}

def bintrayProjects = [ "adblock-android", "adblock-android-settings", "adblock-android-webview" ]

// Sub-projects common config
subprojects {
  repositories {
    google()
    jcenter()
    mavenCentral()
    maven { url 'https://jitpack.io' }
  }

  // apply to all subprojects
  // in order to check a subproject, run gradlew `:<subproj_name>:checkstyle`,
  // for example: `gradlew :adblock-android-settings:checkstyle`
  apply plugin: 'checkstyle'

  checkstyle {
    // assign the latest checkstyle version explicitly
    // the default version is very old, like 5.9
    toolVersion = Vers.checkstyle
    // a reference checkstyle.xml is here:
    // https://raw.githubusercontent.com/checkstyle/checkstyle/checkstyle-8.39/src/main/resources/google_checks.xml
    configFile = rootProject.file('config/checkstyle/checkstyle.xml')
  }

  task checkstyleMain(type: Checkstyle) {
    description 'Check code style of main source set'
    group 'verification'
    source 'src/main/java'
    include '**/*.java'

    // empty classpath
    classpath = rootProject.files()
  }

  task checkstyleAndroidTest(type: Checkstyle) {
    description 'Check code style of android connected tests'
    group 'verification'
    source 'src/androidTest/java'
    include '**/*.java'

    // empty classpath
    classpath = rootProject.files()
  }

  task checkstyleTest(type: Checkstyle) {
    description 'Check code style of tests source set'
    group 'verification'
    source 'src/androidTest/java'
    include '**/*.java'

    // empty classpath
    classpath = rootProject.files()
  }

  tasks.register('checkstyle') {
    dependsOn checkstyleMain
    dependsOn checkstyleTest
    dependsOn checkstyleAndroidTest
  }

  task listAllDependencies(type: DependencyReportTask) {}

  // Configure bintray publication for selected sub-projects
  if (name in bintrayProjects) {

    buildscript {
      repositories {
        maven { url "https://plugins.gradle.org/m2/" }
      }

      dependencies {
        classpath Deps.tools_bintray_gradle_plugin
      }
    }

    // First, let's apply the maven and bintray related plugins
    apply plugin: 'com.jfrog.bintray'
    apply plugin: 'maven'
    apply plugin: 'maven-publish'

    def projectName = hasProperty('libraryName') ? libraryName : project.name

    // Add bintray.pkg.desc per project
    bintray {
      user = hasProperty('bintrayUser') ? project.bintrayUser
              : System.getenv('BINTRAY_USERNAME')
      key = hasProperty('bintrayKey') ? project.bintrayKey
              : System.getenv('BINTRAY_KEY')
      dryRun = project.hasProperty('dryRun') ? project.dryRun.toBoolean() : true
      publish = true
      override = true
      publications = ['artifactPublication']
      pkg {
        issueTrackerUrl = Bintray.issueTracker
        licenses = Bintray.licences
        name = projectName
        repo = 'maven'
        userOrg = Bintray.userOrg
        vcsUrl = Bintray.repository
        websiteUrl = Bintray.website
        version {
          name = Config.moduleVersion
          vcsTag = Config.moduleVersion
        }
      }
    } // end of bintray

    afterEvaluate {

      task androidJavadocs(type: Javadoc) {
        source = android.sourceSets.main.java.srcDirs
        classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
        android.libraryVariants.all { variant ->
          if (variant.name == 'release') {
            owner.classpath += variant.javaCompileProvider.get().classpath
          }
        }
        exclude '**/R.java', '**/R.html', '**/R.*.html', '**/index.html'
        failOnError false
      }

      task sourcesJar(type: Jar) {
        from android.sourceSets.main.java.srcDirs
        archiveClassifier.set("sources")
      }

      task javadocsJar(type: Jar, dependsOn: androidJavadocs) {
        from androidJavadocs.destinationDir
        archiveClassifier.set('javadoc')
      }

      uploadArchives {
        repositories.mavenDeployer {
          pom.groupId = projectName
          pom.artifactId = project.archivesBaseName
          pom.version = Config.moduleVersion
          repository(url: Bintray.repository)
        }
      }

      publishing {
        publications {
          artifactPublication(MavenPublication) {
            // Define this explicitly if using implementation or api configurations
            pom.withXml {
              def dependenciesNode = asNode().getAt('dependencies')[0] ?: asNode()
                      .appendNode('dependencies')

              if (projectName != 'adblock-android') {
                // Maven can't pick up adblock-android dependency right, adding manually
                def dependencyNode = dependenciesNode.appendNode('dependency')
                dependencyNode.appendNode('groupId', 'org.adblockplus')
                dependencyNode.appendNode('artifactId', 'adblock-android')
                dependencyNode.appendNode('version', Config.moduleVersion)
              }

              // Iterate over the implementation dependencies, we don't want the test ones
              configurations.implementation.allDependencies.each {
                if (it.name != 'unspecified' && it.version != 'unspecified') {
                  def dependencyNode = dependenciesNode.appendNode('dependency')
                  dependencyNode.appendNode('groupId', it.group)
                  dependencyNode.appendNode('artifactId', it.name)
                  dependencyNode.appendNode('version', it.version)
                }
              }
            }
            def postfix = projectName == 'adblock-android' ? "-abi_all" : ""
            artifact("$buildDir/outputs/aar/" + projectName + postfix + "-release.aar")
            artifact(sourcesJar)
            artifact(javadocsJar)
            groupId Bintray.groupId
            artifactId projectName
            version Config.moduleVersion
          }
        }
      } // end of publishing
    } // end of afterEvaluate

  } // end of bintray configuration

} // end of sub-projects common config
