/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Synchronize the version in setup.py and the one used in the maven pom.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def currentMavenVersion = project.version as String
def currentPyVersion = currentMavenVersion
if(currentMavenVersion.contains("-SNAPSHOT")) {
    currentPyVersion = currentMavenVersion.split("-SNAPSHOT")[0] + ".dev"
}
println "Current Project Version in Maven:  " + currentMavenVersion

// Sync setup.py
def pyProjectFile = new File(project.basedir, "setup.py")
def match = pyProjectFile.text =~ /version\s*=\s*"(.*?)"/
def pyProjectFileVersion = match[0][1]
println "Current Project Version in setup.py: " + pyProjectFileVersion

if (pyProjectFileVersion != currentPyVersion) {
    pyProjectFile.text = pyProjectFile.text.replace("version = \"" + pyProjectFileVersion + "\"", "version = \"" + currentPyVersion + "\"")
    println "Version in setup.py updated from " + pyProjectFileVersion + " to " + currentPyVersion
} else {
    println "Version in setup.py is up to date"
}

// Sync pyproject.toml
def pyprojectTomlFile = new File(project.basedir, "pyproject.toml")
if (pyprojectTomlFile.exists()) {
    def tomlMatch = pyprojectTomlFile.text =~ /version\s*=\s*"(.*?)"/
    def tomlVersion = tomlMatch[0][1]
    println "Current Project Version in pyproject.toml: " + tomlVersion

    if (tomlVersion != currentPyVersion) {
        pyprojectTomlFile.text = pyprojectTomlFile.text.replaceFirst("version = \"" + tomlVersion + "\"", "version = \"" + currentPyVersion + "\"")
        println "Version in pyproject.toml updated from " + tomlVersion + " to " + currentPyVersion
    } else {
        println "Version in pyproject.toml is up to date"
    }
}
