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() && 1L == match.size() && 5L == 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 28
    buildToolsVersion '28.0.3'

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

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

dependencies {
    implementation 'com.android.support:appcompat-v7:28.0.0'
}
