# Copyright (c) 2009-2011 XORP, Inc and Others
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, Version 2, June
# 1991 as published by the Free Software Foundation. Redistribution
# and/or modification of this program under the terms of any other
# version of the GNU General Public License is not permitted.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For more details,
# see the GNU General Public License, Version 2, a copy of which can be
# found in the XORP LICENSE.gpl file.
#
# XORP Inc, 2953 Bunker Hill Lane, Suite 204, Santa Clara, CA 95054, USA;
# http://xorp.net

# $XORP$

import os, re
Import('env')

e = env.Clone()

cmds = [
    'fea',
    'host',
    'igmp',
    'mfea',
    'misc',
    'mld',
    'pim',
    'policy',
    'rib',
]

tps = [
    'fib2mrib',
    'igmp',
    'interfaces',
    'mfea4',
    'mld',
    'pimsm4',
    'plumbing',
    'policy',
    'protocols',
    'rib',
    'rtrmgr',
    'static_routes',
]

tp_raw = [
    'fea'
    ]

if not (env.has_key('disable_ipv6') and env['disable_ipv6']):
    cmds.append('mfea6')
    tps.append('mfea6')
    cmds.append('pim6')
    tps.append('pimsm6')
    
    if env['enable_ospf']:
        cmds.append('ospfv3')
        tps.append('ospfv3')
        
if not (env.has_key('disable_fw') and env['disable_fw']):
    tps.append('firewall')

if env['enable_olsr']:
    cmds.append('olsr4')
    tps.append('olsr4')

if env['enable_ospf']:
    cmds.append('ospfv2')
    tps.append('ospfv2')

if env['enable_bgp']:
    cmds.append('bgp')
    tps.append('bgp')

if env['enable_rip']:
    cmds.append('rip')
    tps.append('rip')
    cmds.append('ripng')
    tps.append('ripng')

if env['enable_vrrp']:
    cmds.append('vrrp')
    tps.append('vrrp')

if env['enable_xorpsh']:
    cmds.append('xorpsh')

# Total hack for now, might want to consider some sort of lame CPP syntax
# instead of hard-coding the pattern matching below.
def BuildXrlTemplate(target, source, env):
    #    base = tp[:-len('.raw')]
    skip_fw = False
    skip_click = True
    if (env.has_key('disable_fw') and env['disable_fw']):
        skip_fw = True

    if (env.has_key('enable_click') and env['enable_click']):
        skip_click = False

    sfname = str(source[0])
    
    print "source: ", sfname
    print "target: ", str(target[0])
    
    ifile = open(sfname, 'r')
    ofile = open(str(target[0]), 'w')
    
    if sfname == 'etc/templates/fea.tp.raw':
        ignore_ln = re.compile(".*firewall.*")

        opened_brackets = 0
        opened_bracket_ln = re.compile(".*{.*")
        closed_bracket_ln = re.compile(".*}.*")
        click_ln = re.compile(".*click.*")

        for line in ifile.readlines():
            if opened_brackets > 0:
                if opened_bracket_ln.match(line):
                    opened_brackets += 1
                if closed_bracket_ln.match(line):
                    opened_brackets -= 1
                continue
            if (skip_fw and ignore_ln.match(line)):
                continue
            if (skip_click and click_ln.match(line)):
                opened_brackets = 1
                continue
            if line[-1] == "\n":
                # trim trailing newline
                line = line[0 : -1]
                print >>ofile, "%s" % line
    else:
        return -1 # error
    
    return None

bld = Builder(action = BuildXrlTemplate,
              suffix = '.tp',
              src_suffix = '.tp.raw')

e.Append(BUILDERS = {'BuildTP' : bld})


all_tp_raw = []
for tp in tp_raw:
    all_tp_raw.append(e.BuildTP(tp))

Default(all_tp_raw)

if env['enable_builddirrun']:
        template_source_dir = os.path.join(env['xorp_sourcedir'], "etc")
        template_source_dir = os.path.join(template_source_dir, "templates")

        cmd_files = [c.__add__('.cmds') for c in cmds]
        for obj in cmd_files:
		#copy all necessary cmd_files in $BUILDDIR/etc/templates
		Execute(Copy(os.path.join(env['xorp_alias_templatedir'], str(obj)),
			os.path.join(template_source_dir, str(obj))))

        tp_files = [t.__add__('.tp') for t in tps]
        for obj in tp_files:
		#copy all necessary tp_files in $BUILDDIR/etc/templates
		Execute(Copy(os.path.join(env['xorp_alias_templatedir'], str(obj)),
			os.path.join(template_source_dir, str(obj))))

        tp_raw_files = [t.__add__('.tp') for t in tp_raw]
        for obj in tp_raw_files:
		#copy all necessary tp_files in $BUILDDIR/etc/templates
		Execute(Copy(os.path.join(env['xorp_alias_templatedir'], str(obj)),
			os.path.join(template_source_dir, str(obj))))

e.Alias('install', [
        e.InstallData(env['xorp_templatedir'],
                      [c.__add__('.cmds') for c in cmds]),
        e.InstallData(env['xorp_templatedir'],
                      [t.__add__('.tp') for t in tps]),
        e.InstallData(env['xorp_templatedir'],
                      [t.__add__('.tp') for t in tp_raw])
])
