#
# CORE
# Copyright (c)2010-2012 the Boeing Company.
# See the LICENSE file included in this distribution.
#
''' Sample user-defined service.
'''

import os

from core.service import CoreService, addservice
from core.misc.ipaddr import IPv4Prefix, IPv6Prefix

class TrafficDump(CoreService):
    ''' This is a sample user-defined service.
    '''
    # a unique name is required, without spaces
    _name = "TrafficDump"
    # you can create your own group here
    _group = "WAN_BGP"
    # list of other services this service depends on
    _depends = ()
    # per-node directories
    _dirs = ()
    # generated files (without a full path this file goes in the node's dir,
    #  e.g. /tmp/pycore.12345/n1.conf/)
    _configs = ('startdump.sh', )
    # this controls the starting order vs other enabled services
    _startindex = 10
    # list of startup commands, also may be generated during startup
    _startup = ('sh startdump.sh',)
    # list of shutdown commands
    _shutdown = ('killall tcpdump')

    @classmethod
    def generateconfig(cls, node, filename, services):
        ''' Start TCPDUMP on interface eth0. Returns a string that will be written to filename,
            or sent to the GUI for user customization.
        '''
        cfg = "#!/bin/sh\n"
        cfg += "# auto-generated by TrafficDump (trafficdump.py)\n"
        for ifc in node.netifs():
            cfg += 'echo "Node %s has interface %s"\n' % (node.name, ifc.name)
            # here we do something interesting
            cfg += "\n".join(map(cls.subnetentry, ifc.addrlist))
            break
        cfg += "\n"
        cfg += "# Select the interface(s) to dump\n"
        cfg += "tcpdump -U -i eth0 -w - >/home/vagrant/output/traffic-%s-eth0.pcap & \n" % (node.name)
        cfg += "#tcpdump -U -i eth1 -w - >/home/vagrant/output/traffic-%s-eth1.pcap & \n" % (node.name)
        cfg += "#tcpdump -U -i eth2 -w - >/home/vagrant/output/traffic-%s-eth2.pcap & \n" % (node.name)
        cfg += "#tcpdump -U -i eth3 -w - >/home/vagrant/output/traffic-%s-eth3.pcap & \n" % (node.name)
        cfg += "#tcpdump -U -i eth4 -w - >/home/vagrant/output/traffic-%s-eth4.pcap & \n" % (node.name)
        cfg += "#tcpdump -U -i eth5 -w - >/home/vagrant/output/traffic-%s-eth5.pcap & \n" % (node.name)
        cfg += "#tcpdump -U -i eth6 -w - >/home/vagrant/output/traffic-%s-eth6.pcap & \n" % (node.name)
        return cfg

    @staticmethod
    def subnetentry(x):
        ''' Generate a subnet declaration block given an IPv4 prefix string
            for inclusion in the config file.
        '''
        if x.find(":") >= 0:
            # this is an IPv6 address
            return ""
        else:
            net = IPv4Prefix(x)
            return 'echo "  network %s"' % (net)

# this line is required to add the above class to the list of available services
addservice(TrafficDump)
