plugins {
    id 'org.ajoberstar.grgit' version '1.7.1'
    id 'com.palantir.git-version' version '0.7.1'
}

apply plugin: 'com.android.application'

import org.ajoberstar.grgit.Grgit

// Use commit date as version code (valid up to 07/18/2036)
def buildVersionCode() {
    def repo = Grgit.open()
    def head = repo.head()

    // Sanity check across git plugins
    assert head.getAbbreviatedId(10) == versionDetails().gitHash : "Internal error: SHA1 mismatch!"

    return head.time
}

// Derive version name from release tag and add commit SHA1
def buildVersionName() {
    def pattern = /client_release\/\d+\.\d+\/(?<major>\d+)\.(?<minor>\d+)\.(?<revision>\d+)(?<suffix>[-_\.].*)/
    def version = ': DEVELOPMENT'

    def head = versionDetails()
    def tag = head.lastTag
    def match = (tag =~ pattern)

    // Sanity checks for tag format
    if(match.hasGroup() && 1 == match.size() && 5 == match[0].size() && head.commitDistance == 0) {
        def major = match.group('major')
        def minor = match.group('minor')
        def revision = match.group('revision')
        def suffix = match.group('suffix')
        version = "${major}.${minor}.${revision}${suffix}"
        assert !suffix.endsWith('.dirty') : "Dirty working tree detected! Preventing release build!"
    }
    else {
        println "Warning! Non-release tag or offset found: $tag (offset: $head.commitDistance)"
        println "Flagging as DEVELOPMENT build..."
    }

    def commit = versionDetails().gitHash

    return "${version} (${commit})"
}

android {
    compileSdkVersion 23
    buildToolsVersion "25.0.0"

    defaultConfig {
        applicationId "edu.berkeley.boinc"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode buildVersionCode()
        versionName buildVersionName()
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
        debug {
            minifyEnabled false
            debuggable true
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.1.+'
}
