#!/usr/bin/env python

import glob, os, sys
import sipconfig
from PyQt4 import pyqtconfig

def get_diana_version():

    depends = filter(lambda line: line.startswith("Depends:"),
                     open("debian/control").readlines())
    
    for line in depends:
        pieces = line.split()
        for piece in pieces:
            name_pieces = piece.strip(",").split("-")
            if len(name_pieces) == 2 and name_pieces[0] == "diana":
                return name_pieces[1]
    return None

def get_python_diana_version():

    line = open("debian/changelog").readline()
    pieces = line.split()

    return pieces[1][1:-1]


if __name__ == "__main__":

    if len(sys.argv) not in (1, 3, 5):
    
        sys.stderr.write("Usage: %s [<directory containing diana headers> <directory containing libdiana>] "
                         "[<directory containing metlibs headers> <directory containing metlibs libraries>]\n" % sys.argv[0])
        sys.exit(1)
    
    if len(sys.argv) == 5:
        metlibs_inc_dir = sys.argv[3]
        metlibs_lib_dir = sys.argv[4]
    else:
        metlibs_inc_dir = "/usr/include/metlibs"
        metlibs_lib_dir = "/usr/lib"
    
    if len(sys.argv) >= 3:
        diana_inc_dir = sys.argv[1]
        diana_lib_dir = sys.argv[2]
    else:
        diana_inc_dir = "/usr/include/diana"
        diana_lib_dir = "/usr/lib"
    
    qt_pkg_dir = os.getenv("qt_pkg_dir")
    python_diana_pkg_dir = os.getenv("python_diana_pkg_dir")
    dest_pkg_dir = os.path.join(python_diana_pkg_dir, "metno")

    config = pyqtconfig.Configuration()
    
    # The name of the SIP build file generated by SIP and used by the build
    # system.
    sip_files_dir = "sip"
    modules = ["std", "metlibs", "diana"]
    
    if not os.path.exists("modules"):
        os.mkdir("modules")
    
    # Run SIP to generate the code.
    output_dirs = []
    
    for module in modules:
    
        output_dir = os.path.join("modules", module)
        build_file = module + ".sbf"
        build_path = os.path.join(output_dir, build_file)
        
        if not os.path.exists(output_dir):
            os.mkdir(output_dir)
        
        sip_file = os.path.join("sip", module, module+".sip")
        
        command = " ".join([config.sip_bin,
                            "-c", output_dir,
                            "-b", build_path,
                            "-I"+config.sip_inc_dir,
                            "-I"+config.pyqt_sip_dir,
                            "-I"+diana_inc_dir,
                            "-I/usr/include",
                            "-I"+metlibs_inc_dir,
                            "-I"+qt_pkg_dir+"/include",
                            "-I"+qt_pkg_dir+"/share/sip/PyQt4",
                            "-Isip",
                            config.pyqt_sip_flags,
                            "-w",
                            "-o", # generate docstrings for signatures
                            sip_file])
        sys.stdout.write(command+"\n")
        sys.stdout.flush()
        
        if os.system(command) != 0:
            sys.exit(1)
        
        # Create the Makefile (within the diana directory).
        makefile = pyqtconfig.QtGuiModuleMakefile(
            config, build_file, dir=output_dir,
            install_dir=dest_pkg_dir,
            qt=["QtCore", "QtGui", "QtNetwork", "QtXml", "QtXmlPatterns"]
            )
        
        if module == "diana":
            makefile.extra_include_dirs += [
                diana_inc_dir,
                os.path.join(diana_inc_dir, "PaintGL"),
                metlibs_inc_dir,
                qt_pkg_dir+"/include"
                ]
            
            makefile.extra_lib_dirs += [diana_lib_dir, qt_pkg_dir+"/lib"]
            
            makefile.extra_lflags += ["-Wl,-rpath="+diana_lib_dir, "-Wl,-fPIC"]
            makefile.extra_libs += ["diana"]
        
        if module == "metlibs":
            makefile.extra_include_dirs.append(diana_inc_dir)
            makefile.extra_include_dirs.append("/usr/include/metlibs")
            
            makefile.extra_lib_dirs += [diana_lib_dir, "/usr/lib", metlibs_lib_dir, qt_pkg_dir+"/lib"]

            makefile.extra_lflags += ["-Wl,-rpath="+diana_lib_dir, "-Wl,-fPIC"]
            makefile.extra_libs += ["miLogger", "coserver", "diana"]
        
        makefile.generate()
        
        output_dirs.append(output_dir)
    
    # Update the metno package version.
    diana_version = get_diana_version()
    python_diana_version = get_python_diana_version()

    if not diana_version or not python_diana_version:
        sys.stderr.write("Failed to find version information for Diana (%s) "
                         "or python-diana (%s)\n" % (repr(diana_version),
                                                     repr(python_diana_version)))
        sys.exit(1)
    
    f = open("python/metno/versions.py", "w")
    f.write('\ndiana_version = "%s"\npython_diana_version = "%s"\n' % (
        diana_version, python_diana_version))
    
    
    # Generate the top-level Makefile.
    python_files = glob.glob(os.path.join("python", "metno", "*.py"))

    sipconfig.ParentMakefile(
        configuration = config,
        subdirs = output_dirs,
        installs = [(python_files, dest_pkg_dir)]
        ).generate()
    
    sys.exit()

