Ensure a user is present

    .. code-block:: yaml

        ensure example test user 1:
            splunk.user_present:
                - realname: 'Example TestUser1'
                - name: 'exampleuser'
                - email: 'example@domain.com'
                - roles: ['user']

    The following parameters are required:

    email
        This is the email of the user in splunk

def present(email, profile="splunk", **kwargs):
    '''
    Ensure a user is present

    .. code-block:: yaml

        ensure example test user 1:
            splunk.user_present:
                - realname: 'Example TestUser1'
                - name: 'exampleuser'
                - email: 'example@domain.com'
                - roles: ['user']

    The following parameters are required:

    email
        This is the email of the user in splunk
    '''

    name = kwargs.get('name')

    ret = {
        'name': name,
        'changes': {},
        'result': None,
        'comment': ''
    }

    target = __salt__['splunk.get_user'](email, profile=profile, user_details=True)

    if not target:
        if __opts__['test']:
            ret['comment'] = 'User {0} will be created'.format(name)
            return ret

        # create the user
        result = __salt__['splunk.create_user'](
            email, profile=profile, **kwargs
        )
        if result:
            ret['changes'].setdefault('old', None)
            ret['changes'].setdefault('new', 'User {0} exists'.format(name))
            ret['result'] = True
        else:
            ret['result'] = False
            ret['comment'] = 'Failed to create {0}'.format(name)

        return ret
    else:
        ret['comment'] = 'User {0} set to be updated.'.format(name)
        if __opts__['test']:
            ret['result'] = None
            return ret

        # found a user... updating
        result = __salt__['splunk.update_user'](
            email, profile, **kwargs
        )

        if isinstance(result, bool) and result:
            # no update
            ret['result'] = None
            ret['comment'] = "No changes"
        else:
            diff = {}
            for field in ['name', 'realname', 'roles', 'defaultApp', 'tz', 'capabilities']:
                if field == 'roles':
                    diff['roles'] = list(set(target.get(field, [])).symmetric_difference(set(result.get(field, []))))
                elif target.get(field) != result.get(field):
                    diff[field] = result.get(field)

            newvalues = result
            ret['result'] = True
            ret['changes']['diff'] = diff
            ret['changes']['old'] = target
            ret['changes']['new'] = newvalues

    return ret