# Copyright (C) 2002, 2003, 2004 by Intevation GmbH
# Authors:
# Thomas Koester <tkoester@intevation.de>
# Frank Koormann <frank.koormann@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with the software for details.

"""
Thuban version information
"""

__version__ = "$Revision: 1.14 $"
# $Source: /thubanrepository/thuban/Thuban/version.py,v $
# $Id: version.py,v 1.14 2004/02/25 10:33:24 bh Exp $


# Note that this file defines the version number of Thuban for the about
# dialog.

# The thuban version string is build from two values, thuban_branch and
# thuban_release.  If release is "cvs" the code is from a non-released
# cvs version and the version string is built from the branch, the
# release and an approximation of the date (e.g. the most recent date of
# the ChangeLog file or the most recent modification time of a source
# file).  Otherwise the string is build from the branch and the release.
# E.g. given
#
#  thuban_branch = "1.1"
#  thuban_release = "cvs"
#
# the version string will be "Thuban 1.1 cvs 2004-02-24" (obviously the
# actual date might differ :) ).  OTOH, given
#
#  thuban_branch = "1.0"
#  thuban_release = "1"
#
# the version string will be "Thuban 1.0.1"
#

thuban_branch = "1.1"
thuban_release = "cvs"



import sys, os, os.path
import time
from string import split

from Thuban import  _
from Thuban.Lib.version import make_tuple

if __name__ == "__main__":
    import sys
    __file__ = sys.argv[0]

def is_relevant_file(file):
    """check if a file is relevant for determining the current version"""
    extensions = ['.py', '.xpm', '.c', '.h']
    return os.path.isfile(file) and os.path.splitext(file)[1] in extensions

def visit(args, dirname, names):
    """helper for os.path.walk; save mtime of newest file for this directory"""
    files = filter(is_relevant_file,
                   [os.path.join(dirname, file) for file in names])
    args['max'] = max([args['max']] + map(os.path.getmtime, files))

def get_date(format):
    """strftime formatted mtime of the newest relevant file"""
    dir = os.path.dirname(os.path.abspath(__file__))
    args = {'max': 0}
    os.path.walk(dir, visit, args)
    return time.strftime(format, time.localtime(args['max']))

def get_changelog_date():
    changelog = os.path.join(os.path.dirname(__file__), os.pardir, "ChangeLog")
    try:
        file = open(changelog, "r")
        line = file.readline()
        file.close() 
    except:
        return ""
    return 'ChangeLog %s' % line.split(" ")[0]


# 
# Fill in versions with the different versions of the libraries
# that Thuban is using or requires (only if those libraries are
# available.
#

versions = {}

if thuban_release == "cvs":
    version = '%s %s-%s' % (thuban_branch, thuban_release, get_date('%Y%m%d'))
    longversion = '%s\n%s' % (version, get_changelog_date())
else:
    version = thuban_branch + "." + thuban_release
    longversion = 'Release Version ' + version

versions['thuban'] = version
versions['thuban-long'] = longversion

# wxPython
from wxPython.wx import __version__ as wxPython_version
versions['wxPython'] = wxPython_version
versions['wxPython-tuple'] = make_tuple(wxPython_version)

# Python
versions['python'] = "%d.%d.%d" % sys.version_info[:3]
versions['python-tuple'] = sys.version_info[:3]

# PySQLite
from sqlite import version as pysqlite_version
versions['pysqlite'] = pysqlite_version
versions['pysqlite-tuple'] = make_tuple(pysqlite_version)

# SQLite
from _sqlite import sqlite_version
versions['sqlite'] = sqlite_version()
versions['sqlite-tuple'] = make_tuple(sqlite_version())

# GDAL
from  Thuban.Model.resource import has_gdal_support
if has_gdal_support():
    from gdalwarp import get_gdal_version
    versions['gdal'] = get_gdal_version()
    versions['gdal-tuple'] = make_tuple(get_gdal_version())

from wxproj import get_proj_version, get_gtk_version, get_wx_version

# GTK
gtk_ver = get_gtk_version()
if gtk_ver:
    versions['gtk'] = ".".join(map(str, gtk_ver))
    versions['gtk-tuple'] = gtk_ver

# PROJ
proj_ver = get_proj_version()
if proj_ver:
    versions['proj'] = ".".join(map(str, proj_ver))
    versions['proj-tuple'] = proj_ver

wxproj_wx_version = get_wx_version()
versions['wxproj-wx'] = ".".join(map(str, wxproj_wx_version))
versions['wxproj-wx-tuple'] = wxproj_wx_version


# psycopg/postgis
import Thuban.Model.postgisdb
if Thuban.Model.postgisdb.has_postgis_support():
    v = Thuban.Model.postgisdb.psycopg_version()
    versions['psycopg'] = v
    versions['psycopg-tuple'] = make_tuple(v)

def verify_versions():
    """Verify that Thuban is using the correct versions of libraries.

    Returns a non-empty list of strings indicating which libraries
    are wrong, or the empty list if everthing is ok.
    """

    #
    # The 'name' below must correspong to an mapping in 'versions'.
    # There must also exist a 'name'-tuple mapping.
    #
    #         title           name       version
    list = [["Python",      "python",   (2, 2, 1)],
            ["wxPython",    "wxPython", (2, 4, 0)],
            ["SQLite",      "sqlite",   (2, 8, 0)],
            ["PySQLite",    "pysqlite", (0, 4, 1)],
            ["PROJ",        "proj",     (4, 4, 5)],
            ["GTK",         "gtk",      (1, 2, 3)],
            ["GDAL",        "gdal",     (1, 1, 8)]]

    errors = []
    for title, name, version in list:
        tup = versions.get("%s-tuple" % name, None)
        if tup and tup < version:
            errors.append(_("%s %s < %s") % \
                          (title, versions[name], ".".join(map(str, version))))

    # Check whether the wxWindows version of wxPython and thuban's
    # wxproj module match.  If they don't match, segfaults are likely.
    if versions["wxproj-wx-tuple"] != versions["wxPython-tuple"][:3]:
        errors.append(_("Thuban was compiled with wx %(wxproj-wx)s"
                        " but wxPython is %(wxPython)s")
                      % versions)

    return errors

if __name__ == "__main__":
    print longversion

