'Copy actions/roles from hda to ldda.library_dataset (and then ldda) if ldda
doesn\'t already have roles for the given action.'

def _apply_hda_permissions_to_ldda(self, trans, hda, ldda):

    security_agent = trans.app.security_agent
    dataset_permissions_dict = security_agent.get_permissions(hda.dataset)
    library_dataset = ldda.library_dataset
    library_dataset_actions = [permission.action for permission in library_dataset.actions]
    dataset_manage_permissions_action = security_agent.get_action('DATASET_MANAGE_PERMISSIONS').action
    library_manage_permissions_action = security_agent.get_action('LIBRARY_MANAGE').action
    flush_needed = False
    for (action, dataset_permissions_roles) in dataset_permissions_dict.items():
        if isinstance(action, security.Action):
            action = action.action
        if (action == dataset_manage_permissions_action):
            action = library_manage_permissions_action
        if (action not in library_dataset_actions):
            for role in dataset_permissions_roles:
                ldps = trans.model.LibraryDatasetPermissions(action, library_dataset, role)
                ldps = ([ldps] if (not isinstance(ldps, list)) else ldps)
                for ldp in ldps:
                    trans.sa_session.add(ldp)
                    flush_needed = True
    if flush_needed:
        trans.sa_session.flush()
    security_agent.copy_library_permissions(trans, library_dataset, ldda)
    return security_agent.get_permissions(ldda)
