buildscript {
  repositories {
    jcenter()
  }

  dependencies {
    classpath "org.ajoberstar.grgit:grgit-gradle:3.0.0"
  }
}

ext {
  releaseNotes = "$project.buildDir/reports/release-notes.log"
  commitMessage = gitReleaseNotes()

  VERSION_CODE = gitTagCount()
  VERSION_NAME = gitTagName()
}

def gitReleaseNotes() {
  def command = "mkdir -p \$(dirname ${project.ext.releaseNotes}) &&"
  command += " git log `git describe --tags --match '[0-9]*.[0-9]*.[0-9]*' --abbrev=0`..HEAD --oneline |"
  command += " sort -d |"
  command += " tee ${project.ext.releaseNotes}"

  print(command)
  def process = ['sh', '-c', command].execute()
  process.waitFor()
  process.text
}

task gitReleaseNotes { Task task ->
  doLast {
    println gitReleaseNotes()
    println "Release notes are also saved in ${project.ext.releaseNotes}"
  }
}

def gitTagCount() {
  def git = org.ajoberstar.grgit.Grgit.open(currentDir: projectDir)
  git.tag.list().size()
}

def gitTagName() {
  def git = org.ajoberstar.grgit.Grgit.open(currentDir: projectDir)
  git.tag.list().last().getName()
}
