#!/usr/bin/env python
#
# Python script for checking versions of python, java and mosflm
#

#
# Welcome message
#

PYTHON_MIN_VERSION = (2,4)
JAVA_MIN_VERSION = (1,4,2)

import os, sys, string

VERBOSE = 0

if len(sys.argv) > 1:
    # changed the check to allow more command line options
    if "-v" in sys.argv:
        VERBOSE = True

def vprint(text=""):
    if VERBOSE:
        print text

vprint("-------------------------------------------------")
vprint()
vprint("Test of the DNA installation.")
vprint("Checking versions of Python and Java:")
vprint()

#
# Start with python, check that we have a correct version
#

try:
    vprint("Checking the Python version: %s\n" % sys.version)
    version_info = sys.version_info
    if version_info[:3] < PYTHON_MIN_VERSION:
        print "Wrong version of python: %s" % sys.version
        print "DNA requires version %d.%d or higher" % (PYTHON_MIN_VERSION[0], PYTHON_MIN_VERSION[1])
        sys.exit(1)
    vprint("This version of Python ok.\n")
except:
    print "ERROR during python version check."
    raise

#
# Now check the version of java
#

if "DNAJDK" in os.environ.keys():
    DNAJDK=os.getenv("DNAJDK")
    JAVA_PATH=os.path.join(DNAJDK,"bin","java")
else:
    JAVA_PATH="java"

vprint("Using the following java command: %s" % JAVA_PATH)

try:
    vprint("Checking the java version:")
    os.system("rm -rf java.tmp")
    os.system("bash -c \"%s -version > /tmp/java.tmp 2>&1\"" % JAVA_PATH)
    if VERBOSE:
        os.system("cat /tmp/java.tmp")
        print
    f = open("/tmp/java.tmp")
    java_version = f.readline()
    f.close()
    os.system("/bin/rm -f /tmp/java.tmp")
    if string.find(java_version, "command not found") != -1:
        print "ERROR - no java command available!"
        print "Make sure that java version 1.4.2 or higher is installed"
        print "and that the path is correctly configured."
        sys.exit(1)
    vprint(java_version+"\n")
    version_string = java_version.split()[2].replace('"', '').split(".")

    #
    # The following code is necessary for catching minor
    # version of type "1_02".
    #
    index = string.find(version_string[2],"_")
    if index == -1:
        index = string.find(version_string[2],"-")
    if index != -1:
        version_string[2] = version_string[2][0:index]
    else:
        index = string.find(version_string[2],"_")
	if index != -1:
	    version_string[2] = version_string[2][0:index]
    version_string = tuple(map(int, version_string))
    if version_string < JAVA_MIN_VERSION:
        print "You don't have the required version of java."
        print "Please install version 1.4.2 or higher."
        sys.exit(1)
    vprint("This version of java is ok.\n")
except:
    print "ERROR during java version check."
    raise

vprint("DNA Python and Java version checks ok.")
   
