// Code by @IlyaEremin
//
// See description at https://medium.com/@IlyaEremin/npm-version-for-gradle-android-9137a7dc273c

def getVersionName = { getVersionProps()['appVersionName'] }

def getAppVersionCode() { getVersionProps()['appVersionCode'].toInteger() }

def getVersionProps() {
    def versionPropsFile = file('gradle.properties')
    if (!versionPropsFile.exists()) {
        versionPropsFile.createNewFile()
    }
    def versionProps = new Properties()
    versionProps.load(new FileInputStream(versionPropsFile))
    return versionProps
}

def getVersionNamePatch = { (getVersionName() =~ /\d+/)[2].toInteger() }

def getVersionNameMinor = { (getVersionName() =~ /\d+/)[1].toInteger() }

def getVersionNameMajor = { (getVersionName() =~ /\d+/)[0].toInteger() }

private void commitAndSetTag(versionName) {
    Process createCommit = ['git', 'commit', "-m Release ${versionName}"].execute(null,  project.rootDir)
    createCommit.waitForProcessOutput(System.out, System.err)

    Process createTag = ['git', 'tag', "v${versionName}".toString()].execute(null, project.rootDir)
    createTag.waitForProcessOutput(System.out, System.err)
}

private void save(major, minor, patch, versionCode) {
    save("${major}.${minor}.${patch}".toString(), versionCode.toString())
}

private void save(versionName, versionCode) {
    def versionProps = getVersionProps()
    versionProps['appVersionName'] = versionName
    versionProps['appVersionCode'] = versionCode
    versionProps.store(file('gradle.properties').newWriter(), null)
    commitAndSetTag(versionName)
}

task bumperVersionPatch () {
    group = 'bumper'
    doLast {
        save(getVersionNameMajor(), getVersionNameMinor(), getVersionNamePatch() + 1, getAppVersionCode() + 1)
    }
}

task bumperVersionMinor () {
    group = 'bumper'
    doLast {
        save(getVersionNameMajor(), getVersionNameMinor() + 1, 0, getAppVersionCode() + 1)
    }
}

task bumperVersionMajor () {
    group = 'bumper'
    doLast {
        save(getVersionNameMajor() + 1, 0, 0, getAppVersionCode() + 1)
    }
}