#!/usr/bin/env python
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
# Copyright (C) 2008-2026 German Aerospace Center (DLR) and others.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.0/
# This Source Code may also be made available under the following Secondary
# Licenses when the conditions for such availability set forth in the Eclipse
# Public License 2.0 are satisfied: GNU General Public License, version 2
# or later which is available at
# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later

# @file    version.py
# @author  Michael Behrisch
# @author  Daniel Krajzewicz
# @author  Jakob Erdmann
# @date    2007

"""
This script rebuilds "<BUILD_DIR>/src/version.h", the file which
 lets the applications know the version of their build.
It does this by parsing the output of git describe where the function is
 implemented in sumolib.
If the version file is newer than the .git index file or the revision cannot be
determined any existing version.h is kept.
"""
from __future__ import absolute_import
from __future__ import print_function

import sys
from os.path import dirname, exists, getmtime, join, abspath

sys.path.append(dirname(dirname(abspath(__file__))))
import sumolib  # noqa


SUMO_ROOT = abspath(join(dirname(__file__), '..', '..'))


def get_version(padZero=True):
    return sumolib.version.gitDescribe(gitDir=join(SUMO_ROOT, ".git"), padZero=padZero)


def get_pep440_version():
    v = get_version(padZero=False).replace("_", ".").replace("+", ".post")
    if v.endswith("-" + (10 * "0")):
        # this is a fake version number since we could only determine the last release number, see #14228
        return v[:-11] + ".post0"
    v = v[1:v.rfind("-")]
    vs = v.split(".")
    if len(vs) == 4 and vs[3] == "post0":
        return v[:-6]
    return v


def create_version_file(versionFile, revision):
    with open(versionFile, 'w') as f:
        print('#define VERSION_STRING "%s"' % revision, file=f)


def filter_pep440(input_name, output_name):
    with open(input_name) as inf:
        inp = inf.read()
    with open(output_name, "w") as outf:
        outf.write(inp.replace('0.0.0', get_pep440_version()))


def filter_setup_py(in_file, out_file):
    with open(in_file) as inf, open(out_file, "w") as outf:
        for line in inf:
            if line.startswith("package_dir = "):
                print('package_dir = os.path.dirname(os.path.abspath(__file__))', file=outf)
            elif line.startswith("SUMO_VERSION = "):
                print('SUMO_VERSION = "%s"' % get_pep440_version(), file=outf)
            elif not line.startswith("import version"):
                outf.write(line)


def main():
    if len(sys.argv) > 2:
        if sys.argv[1] == "--pep440":
            filter_pep440(sys.argv[2], sys.argv[3 if len(sys.argv) > 3 else 2])
        else:
            filter_setup_py(sys.argv[1], sys.argv[2])
        return
    # determine output file
    if len(sys.argv) > 1:
        versionDir = sys.argv[1]
        if sys.argv[1] == "-":
            sys.stdout.write(get_version())
            return
    else:
        versionDir = join(SUMO_ROOT, "src")
    versionFile = join(versionDir, 'version.h')

    vcsFile = join(SUMO_ROOT, ".git", "index")
    try:
        if exists(vcsFile):
            if not exists(versionFile) or getmtime(versionFile) < getmtime(vcsFile):
                # vcsFile is newer. lets update the revision number
                print('generating %s from revision in %s' % (versionFile, vcsFile))
                create_version_file(versionFile, get_version())
        else:
            print("version control file '%s' not found" % vcsFile)
        if not exists(versionFile):
            print('trying to generate version file %s from existing header' % versionFile)
            create_version_file(versionFile, sumolib.version.fromVersionHeader())
    except Exception as e:
        print("Error creating", versionFile, e)
        try:
            # try at least to create something
            create_version_file(versionFile, "UNKNOWN")
        except Exception as ee:
            print("Error creating", versionFile, ee)
            pass


if __name__ == "__main__":
    main()
