import SCons

# ----------------------------------------------------------------------
# Version generation
# Inject build timestamp and an arbitrary build name into the version label
#
# LATER: it would be useful to integrate this into the VersionStandalone build
# The dynamic build label is added to the *_version.cpp file to avoid complicating
# *_build.h, which is generated by VersionStandalone object. This decision could 
# be revisited when updating VersionStandalone -- though it would be nice to avoid 
# checking in dynamic info like the build timestamp. 

from string import Template
import datetime
import imp

def load_current_version(module_name, version_file, version_attr = ''):
    '''Read and parse the version files to get the current version.
    Returns: the current version structure
    '''
    module = imp.load_source(module_name, version_file)
    current_version = [v for v in getattr(module, version_attr)]
    return current_version

def version_action(target, source, env):
    """
    Generate the *_version.cpp file with the correct version and build date
    in it
    """
    TIME_FORMAT = '%Y/%m/%d %H:%M:%S'
    ver_subst = {
        'VER_TIMESTAMP': datetime.datetime.now().strftime(TIME_FORMAT),
        'VER_BUILD_NAME': env['build_name'], 
    }

    if 'VERSION_MODULE' in env:
        module_name = env['VERSION_MODULE']
        version_file = module_name + '.py'
        version_attr = 'VERSION'
        current_version = load_current_version(module_name, version_file, version_attr)
        ver_subst['VER_BUILD_VERSION'] = current_version[3]
        
    with open(str(source[0]), 'r') as inf:
        template_data = inf.read()
    tmpl = Template(template_data)
    with open(str(target[0]), 'w') as outf:
        outf.write(tmpl.substitute(ver_subst))
    return 0


def init(env) :
    version_bld = SCons.Builder.Builder(action = SCons.Action.Action(version_action, ' [VERSION] $SOURCES'))
    env.Append(BUILDERS = {'VersionFile': version_bld})



