# -*- coding: UTF8 -*-
# vim:filetype=python

import os

import SCons

import racy
import racy.rlog as rlog
#import racy.rlibext as rlibext

EnsureSConsVersion(1, 3, 0)
EnsurePythonVersion(2, 7)

# Empty the Default tools list, avoid useless lookup into it.  
# Speed up about a few seconds
###############################################################################
SCons.Defaults.DefaultEnvironment(tools = [])

try:

    racy.renv.register_env()
    import racy.rlibext as rlibext
    racy.load_plugins()
    racy.renv.check_env()
    racy.rlibext.load_binpkgs()


    env = racy.renv.get_scons_env( tools=[ 'packaging' ] )
except racy.RacyException, e:
    racy.print_error(e.__class__.__name__, e)
    exit(1)


############################################################################
#hosts = {                                                                 #
##        'vincent-i7' : ('192.168.3.24', '8' ), #vincent-i7               #
##        'julien-i7'  : ('192.168.3.10', '8' ), #julien-i7                #
##        'arnaud-i7'  : ('192.168.3.26', '8' ), #arnaud-i7                #
##        'nicolas-i7' : ('192.168.3.23', '8' ), #nicolas-i7               #
#        }                                                                 #
#                                                                          #
#distcc_dir = '/usr/lib/distcc'                                            #
#                                                                          #
#if hosts and os.path.isdir(distcc_dir):                                   #
#    e = env['ENV']                                                        #
#    env.PrependENVPath('PATH',distcc_dir)                                 #
#    e['DISTCC_HOSTS'] = ' '.join(['/'.join(el) for el in hosts.values()]) #
#    e['DISTCC_DIR']   = os.path.expanduser('~/.distcc')                   #
#                                                                          #
#    for h in hosts.keys():                                                #
#        rlog.info.log("Use distcc hosts", h)                              #
#                                                                          #
#    num_jobs = sum(int(n) for ip,n in hosts.values())                     #
#                                                                          #
#    env.SetOption('num_jobs', num_jobs)                                   #
#                                                                          #
############################################################################

rlog.info.log("Debug mode"  , racy.renv.options.get_option('DEBUG'))
rlog.info.log("Nb jobs", env.GetOption('num_jobs'))


rlog.info.log('ARCH', racy.renv.options.get_option('ARCH'))
rlog.info.log('RACY_CONFIG_DIR' , racy.renv.dirs.config )
rlog.info.log('RACY_BUILD_DIR'  , racy.renv.dirs.build  )
rlog.info.log('RACY_INSTALL_DIR', racy.renv.dirs.install)
rlog.info.log('RACY_BINPKGS_DIR' , racy.renv.dirs.binpkg )
rlog.info.log('RACY_CODE_DIRS'  , racy.renv.dirs.code   )

racy.print_msg(rlog.info)

import atexit
def bf_to_str(bf):
    """Convert an element of GetBuildFailures() to a string
    in a useful way."""
    import SCons.Errors
    if bf is None: # unknown targets product None in list
        return '(unknown tgt)'
    elif isinstance(bf, SCons.Errors.StopError):
        return str(bf)
    elif bf.node:
        return str(bf.node) + ': ' + bf.errstr
    elif bf.filename:
        return bf.filename + ': ' + bf.errstr
    return 'unknown failure: ' + bf.errstr

def build_status():
    """Convert the build status to a 2-tuple, (status, msg)."""
    from SCons.Script import GetBuildFailures
    bf = GetBuildFailures()
    if bf:
        # bf is normally a list of build failures; if an element is None,
        # it's because of a target that scons doesn't know anything about.
        status = 'failed'
        failures_message = "\n".join(["Failed building %s" % bf_to_str(x)
                            for x in bf if x is not None])
    else:
        # if bf is None, the build completed successfully.
        if racy.errors:
            status = 'failed'
        else:
            status = 'ok'
        failures_message = ''
    return (status, failures_message)

import atexit
@atexit.register
def display_build_status():
    """Display the build status.  Called by atexit.
    Here you could do all kinds of complicated things."""
    status, failures_message = build_status()
    if status == 'failed':
        print "Build failed"

    print failures_message
    if status == 'ok':
        print 'Racy done.'

