#!/usr/bin/env python

# An example script leveraging the storyboard scripting functionality
from functools import partial

from rumba.storyboard import *
from rumba.model import *
import rumba.log as log
import rumba.testbeds.local as local
import rumba.prototypes.ouroboros as our
from rumba.utils import ExperimentManager
import rumba.utils as utils

log.set_logging_level(log.DEBUG)


n1 = UnicastLayer("n1")

n1.add_policy("rmt.pff", "lfa")
n1.add_policy("security-manager", "passwd")

e1 = EthDixLayer("e1")

node_a = Node("node_a",
              layers=[n1, e1],
              registrations={n1: [e1]})

node_b = Node("node_b",
              layers=[e1, n1],
              registrations={n1: [e1]})

tb = local.Testbed(exp_name="script_test")

exp = our.Experiment(tb, nodes=[node_a, node_b])


client_a = Client(
    "operf",
    options="-d <duration> -s 1000",
    shutdown="",
    c_id='operf_a'
)

client_b = Client(
    "operf",
    options="-d <duration> -s 1000 -n operfb",
    shutdown="",
    c_id='operf_b'
)

client_c = Client(
    "operf",
    options="-d <duration> -s 1000 -n operfc",
    shutdown="",
    c_id='operf_c'
)

server_a = Server(
    "operf",
    options="-l",
    arrival_rate=1,
    mean_duration=5,
    clients=[client_a],
    s_id='server_a'
)

server_b = Server(
    "operf",
    options="-l -n operfb",
    arrival_rate=0.5,
    mean_duration=10,
    clients=[client_b],
    s_id='server_b'
)

server_c = Server(
    "operf",
    options="-l -n operfc",
    arrival_rate=1.6,
    mean_duration=3,
    clients=[client_c],
    s_id='server_c'
)

typewriter = Client(
    "touch test_file",
    shutdown=""
)


if __name__ == '__main__':
    story = StoryBoard(30)
    story.set_experiment(exp)
    story.add_server_on_node(server_a, node_a)
    story.add_server_on_node(server_b, node_a)
    story.add_server_on_node(server_c, node_a)
    client_a.add_node(node_b)
    client_b.add_node(node_b)
    client_c.add_node(node_b)
    script_file = os.path.join(
        os.path.dirname(__file__),
        'example-script.rsb'
    )
    story.parse_script_file(script_file)
    cb = partial(story.run_command, node_a, "ls -l test_file")
    # This will return a file, because it will run after
    # Triggering_event
    action = partial(story.run_client, typewriter, 0.2, node=node_a, callback=cb)
    story.add_event(Event(action, ev_time=12, ev_id='Triggering_event'))
    log.flush_log()
    with ExperimentManager(exp):
        exp.swap_in()
        exp.bootstrap_prototype()
        story.start()
