import re


def make_role_node_dict(target_dict, nodes):
    """Given the target dict containing targets grouped by nodes and the list of
       nodes, this function returns a dictionary containing the list of nodes
       grouped by target and by role:

       {
            'role1':
                {
                    'target1a': ['node1aa', 'node1ab'],
                    'target1b': ['node1ba']
                },
            'role2':
                {
                    'target2a': ['node2aa']
                }
       }

    """
    result_dict = {}

    for role in target_dict.keys():
        result_dict[role] = {}
        for target in target_dict[role]:
            result_dict[role][target] = []
            if target[:2] == 'E@':
                # target is a regular expression
                target_re = re.compile(target[2:])
                for node in nodes:
                    if target_re.match(node):
                        result_dict[role][target].append(node)
            else:
                # assume target is hostname
                result_dict[role][target].append(target)
    return result_dict