#!/usr/bin/env python

"""
Run scons -h to display the associated help, or look below ..
"""

BOLD   ="\033[1m"
RED    ="\033[91m"
GREEN  ="\033[92m"
YELLOW ="\033[1m" #"\033[93m" # unreadable on white backgrounds
CYAN   ="\033[96m"
NORMAL ="\033[0m"

def exists(env):
    return true

def printColorCoded(msg):
    msg = msg.replace(']', NORMAL)
    msg = msg.replace('b[', BOLD)
    msg = msg.replace('g[', GREEN)
    msg = msg.replace('r[', RED)
    msg = msg.replace('c[', CYAN)
    msg = msg.replace('y[', YELLOW)

    print msg

def generate(env):
    import SCons.Util, os

    env.addHelpText("""b[hi]
b[*** abakus options ***
----------------------]
b[* bison=(no|yes): Enable parser support.  Only needed for developers.
b[* flex=(no|yes): Enable lexer support.  Only needed for developers.
b[* mpfr=(no|yes|check): Enable the MPFR library, which is faster and more
                         precise than abakus's high-precision code.

ie: b[scons configure]
""")

    if env['HELP']:
        # Don't even bother.
        return env

    from SCons.Options import Options, PackageOption, EnumOption
    import os

    def CheckFlags(context):
        context.Message('Checking if ld supports --as-needed... ')
        lastLINKFLAGS = context.env['LINKFLAGS']
        context.env.Append(LINKFLAGS = '-Wl,--as-needed')

        ret = context.TryLink("""
#include <iostream>
using namespace std;
int main()
{
    cout << "Test" << endl;
}
""", ".cpp")
        if not ret:
            context.env.Replace(LINKFLAGS = lastLINKFLAGS)
        context.Result(ret)
        return ret

    def CheckPath(context, prog, versionFlag = ''):
        if context.env[prog] == 'yes':
            context.env[prog] = prog

        context.Message('Checking for %s... ' % prog)

        ret = True

        # If absolute path, just try this one.
        if prog[0] == '/':
            ret = context.TryAction('%s %s' % (context.env[prog], versionFlag))[0]
            if ret:
                context.Result(ret)
                return True
            
        path = context.env.WhereIs(prog)
        if ret and path != None:
            context.env[prog] = path
            context.Result(1)
        else:
            context.env[prog] = False
            context.Result(0)
        
            print """
The $foo program was not found!  You asked to use it so we will stop here. It
is not required, you may use $foo=no on the command line to go without it.""".replace('$foo', prog)

            Exit(1)

            return False
            
        context.Result(1)
        return True

    cachefile = env['CACHEDIR'] + '/abakus.cache.py'

    fixup = lambda x: "%s installed here (yes = search)" % x

    opts = None
    if env.doConfigure():
        opts = Options(None, env['ARGS'])
    else:
        opts = Options(cachefile, env['ARGS'])

    opts.AddOptions(
        PackageOption('bison', fixup('use the Bison parser generator'), 'yes'),
        PackageOption('flex', fixup('use the Flex scanner generator'), 'yes'),
        EnumOption ('mpfr', 'use the MPFR high-precision library', 'check',
                    allowed_values=('yes', 'no', 'check'), map={}, ignorecase=1),
        ('ABAKUS_CONFIGURED', '', 0),
        ('HAVE_ASNEEDED', '', 0)
    )

    # We must manually pass the ARGS in.
    opts.Update(env, env['ARGS'])

    if env.doConfigure() or not env['ABAKUS_CONFIGURED']:
        # Configure stuff
        conf = env.Configure(custom_tests = {'CheckPath': CheckPath, 'CheckFlags' : CheckFlags})

        if env['bison'] and env['bison'] != 'no':
            conf.CheckPath('bison', '-V')
        if env['flex'] and env['flex'] != 'no':
            conf.CheckPath('flex', '-V')
        if env['mpfr'] != 'no':
            oldLibs = conf.env.get('LIBS', '')
            conf.env.AppendUnique(LIBS = 'gmp')

            if conf.CheckLibWithHeader('mpfr', 'mpfr.h', 'c++', '''
mpfr_t a;
mpfr_ptr ptr;
__mpfr_struct debug;

mpfr_init(a);
''', autoadd = True):
                env['mpfr'] = 'yes'
            else:
                conf.env.Replace(LIBS = oldLibs)

                if env['mpfr'] == 'yes':
                    print "Unable to find requested library mpfr!"
                    env.Exit(1)
                else:
                    env['mpfr'] = 'no'

        env['HAVE_ASNEEDED'] = 0
        if conf.CheckFlags():
            env['HAVE_ASNEEDED'] = 1

        env['ABAKUS_CONFIGURED'] = 1
        env = conf.Finish()

        try:
            f = open("config.h", "w+")
            f.write("""/* config.h -- Automatically generated by abakus.py
 * Any changes you make to this file will be overwritten!
 */

""")
            f.write("/* HAVE_MPFR -- Defined if the MPFR library is being used. */\n")
            if env['mpfr'] == 'yes':
                f.write ("#define HAVE_MPFR 1\n")
            else:
                f.write ("/* #undef HAVE_MPFR */\n")

            f.close()

        except IOError:
            print "Unable to write config.h!"

        opts.Save(cachefile, env)

# vim: set et ts=8 sw=4:
