/**
 * Copyright 2016 Avinash Ananth Narayan R
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
buildscript {
    dependencies {
        //noinspection GradleDynamicVersion
        classpath "org.eclipse.jgit:org.eclipse.jgit:4.1.1.+"
    }
    repositories {
        jcenter()
    }
}

import org.eclipse.jgit.api.Git
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.storage.file.FileRepositoryBuilder

import static org.eclipse.jgit.lib.Constants.MASTER

def noGit = false
def gitRepo
def git
try {
    gitRepo = new FileRepositoryBuilder()
            .readEnvironment()
            .findGitDir()
            .build()
    git = Git.wrap(gitRepo)
} catch (ignore) {
    println("WARN: No git repository.")
    noGit = true;
}

ext.readVersionCode = {
    def count = 0
    if (noGit) {
        count = 1
    } else {
        def walk = new RevWalk(gitRepo)
        def masterRef = gitRepo.getRef(MASTER)
        if (masterRef == null) {
            return 1;
        }
        def head = walk.parseCommit(masterRef.getObjectId())
        try {
            while (head != null) {
                count++
                def parents = head.getParents()
                if (parents != null && parents.length > 0) {
                    head = walk.parseCommit(parents[0])
                } else {
                    head = null
                }
            }
            walk.dispose()
        } finally {
            walk.close()
        }
    }
    println("using version code: $count")
    return count
}

ext.readVersionName = {
    def version;
    try {
        if (noGit) {
            return "1.0"
        }
        def tag = git.describe().setLong(false).call()
        def clean = git.status().call().isClean()
        version = tag + (clean ? '' : '-dirty')
    } catch (ignore) {
        version = "1.0"
    }
    println("using version name: $version")
    return version
}
