# Path: ansible/module_utils/hashivault.py
# def hashivault_argspec():
#     argument_spec = dict(
#         url=dict(required=False, default=os.environ.get('VAULT_ADDR', ''), type='str'),
#         ca_cert=dict(required=False, default=os.environ.get('VAULT_CACERT', ''), type='str'),
#         ca_path=dict(required=False, default=os.environ.get('VAULT_CAPATH', ''), type='str'),
#         client_cert=dict(required=False, default=os.environ.get('VAULT_CLIENT_CERT', ''), type='str'),
#         client_key=dict(required=False, default=os.environ.get('VAULT_CLIENT_KEY', ''), type='str'),
#         verify=dict(required=False, default=(not os.environ.get('VAULT_SKIP_VERIFY', '')), type='bool'),
#         authtype=dict(required=False, default=os.environ.get('VAULT_AUTHTYPE', 'token'), type='str'),
#         login_mount_point=dict(required=False, default=os.environ.get('VAULT_LOGIN_MOUNT_POINT', None), type='str'),
#         token=dict(required=False, fallback=(hashivault_default_token, ''), type='str', no_log=True),
#         username=dict(required=False, default=os.environ.get('VAULT_USER', ''), type='str'),
#         password=dict(required=False, fallback=(env_fallback, ['VAULT_PASSWORD']), type='str', no_log=True),
#         role_id=dict(required=False, fallback=(env_fallback, ['VAULT_ROLE_ID']), type='str', no_log=True),
#         secret_id=dict(required=False, fallback=(env_fallback, ['VAULT_SECRET_ID']), type='str', no_log=True),
#         aws_header=dict(required=False, fallback=(env_fallback, ['VAULT_AWS_HEADER']), type='str', no_log=True),
#         namespace=dict(required=False, default=os.environ.get('VAULT_NAMESPACE', None), type='str')
#     )
#     return argument_spec
# 
# Path: ansible/module_utils/hashivault.py
# @hashiwrapper
# def hashivault_read(params):
#     result = {"changed": False, "rc": 0}
#     client = hashivault_auth_client(params)
#     version = params.get('version')
#     mount_point = params.get('mount_point')
#     secret = params.get('secret')
#     secret_version = params.get('secret_version')
# 
#     key = params.get('key')
#     default = params.get('default')
#     if secret.startswith('/'):
#         secret = secret.lstrip('/')
#         mount_point = ''
#     if mount_point:
#         secret_path = '%s/%s' % (mount_point, secret)
#     else:
#         secret_path = secret
# 
#     try:
#         if version == 2:
#             response = client.secrets.kv.v2.read_secret_version(secret, mount_point=mount_point, version=secret_version)
#         else:
#             response = client.secrets.kv.v1.read_secret(secret, mount_point=mount_point)
#     except InvalidPath:
#         response = None
#     except Exception as e:
#         result['rc'] = 1
#         result['failed'] = True
#         error_string = "%s(%s)" % (e.__class__.__name__, e)
#         result['msg'] = u"Error %s reading %s" % (error_string, secret_path)
#         return result
#     if not response:
#         if default is not None:
#             result['value'] = default
#             return result
#         result['rc'] = 1
#         result['failed'] = True
#         result['msg'] = u"Secret %s is not in vault" % secret_path
#         return result
#     if version == 2:
#         try:
#             data = response.get('data', {})
#             metadata = data.get('metadata', {})
#             data = data.get('data', {})
#         except Exception:
#             data = str(response)
#     else:
#         data = response['data']
#         metadata = {}
#     lease_duration = response.get('lease_duration', None)
#     if lease_duration is not None:
#         result['lease_duration'] = lease_duration
#     lease_id = response.get('lease_id', None)
#     if lease_id is not None:
#         result['lease_id'] = lease_id
#     renewable = response.get('renewable', None)
#     if renewable is not None:
#         result['renewable'] = renewable
#     wrap_info = response.get('wrap_info', None)
#     if wrap_info is not None:
#         result['wrap_info'] = wrap_info
#     if key and key not in data:
#         if default is not None:
#             result['value'] = default
#             return result
#         result['rc'] = 1
#         result['failed'] = True
#         result['msg'] = u"Key %s is not in secret %s" % (key, secret_path)
#         return result
#     if key:
#         value = data[key]
#     else:
#         value = data
#     result['value'] = value
#     result['metadata'] = metadata
#     return result


import os
import sys
from ansible.errors import AnsibleError
from ansible.module_utils.basic import AnsibleFallbackNotFound
from ansible.plugins.lookup import LookupBase
from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_read




class LookupModule(LookupBase):

    def _get_params(self, argspec, terms, kwargs):
        params = {}
        for arg in argspec:
            spec = argspec[arg]
            if arg in kwargs:
                params[arg] = kwargs[arg]
            elif 'default' in spec:
                params[arg] = spec.get('default')
            elif 'fallback' in spec:
                fall_func, fall_args = spec.get('fallback')
                try:
                    params[arg] = fall_func(*tuple(fall_args))
                except AnsibleFallbackNotFound:
                    pass

        params['secret'] = terms[0]
        try:
            params['key'] = terms[1]
        except IndexError:
            params['key'] = None
        return params

    def run(self, terms, variables=None, **kwargs):
        # self._display.v('Running lookup')

# Path: ansible/module_utils/hashivault.py
# def hashivault_argspec():
#     argument_spec = dict(
#         url=dict(required=False, default=os.environ.get('VAULT_ADDR', ''), type='str'),
#         ca_cert=dict(required=False, default=os.environ.get('VAULT_CACERT', ''), type='str'),
#         ca_path=dict(required=False, default=os.environ.get('VAULT_CAPATH', ''), type='str'),
#         client_cert=dict(required=False, default=os.environ.get('VAULT_CLIENT_CERT', ''), type='str'),
#         client_key=dict(required=False, default=os.environ.get('VAULT_CLIENT_KEY', ''), type='str'),
#         verify=dict(required=False, default=(not os.environ.get('VAULT_SKIP_VERIFY', '')), type='bool'),
#         authtype=dict(required=False, default=os.environ.get('VAULT_AUTHTYPE', 'token'), type='str'),
#         login_mount_point=dict(required=False, default=os.environ.get('VAULT_LOGIN_MOUNT_POINT', None), type='str'),
#         token=dict(required=False, fallback=(hashivault_default_token, ''), type='str', no_log=True),
#         username=dict(required=False, default=os.environ.get('VAULT_USER', ''), type='str'),
#         password=dict(required=False, fallback=(env_fallback, ['VAULT_PASSWORD']), type='str', no_log=True),
#         role_id=dict(required=False, fallback=(env_fallback, ['VAULT_ROLE_ID']), type='str', no_log=True),
#         secret_id=dict(required=False, fallback=(env_fallback, ['VAULT_SECRET_ID']), type='str', no_log=True),
#         aws_header=dict(required=False, fallback=(env_fallback, ['VAULT_AWS_HEADER']), type='str', no_log=True),
#         namespace=dict(required=False, default=os.environ.get('VAULT_NAMESPACE', None), type='str')
#     )
#     return argument_spec
# 
# Path: ansible/module_utils/hashivault.py
# @hashiwrapper
# def hashivault_read(params):
#     result = {"changed": False, "rc": 0}
#     client = hashivault_auth_client(params)
#     version = params.get('version')
#     mount_point = params.get('mount_point')
#     secret = params.get('secret')
#     secret_version = params.get('secret_version')
# 
#     key = params.get('key')
#     default = params.get('default')
#     if secret.startswith('/'):
#         secret = secret.lstrip('/')
#         mount_point = ''
#     if mount_point:
#         secret_path = '%s/%s' % (mount_point, secret)
#     else:
#         secret_path = secret
# 
#     try:
#         if version == 2:
#             response = client.secrets.kv.v2.read_secret_version(secret, mount_point=mount_point, version=secret_version)
#         else:
#             response = client.secrets.kv.v1.read_secret(secret, mount_point=mount_point)
#     except InvalidPath:
#         response = None
#     except Exception as e:
#         result['rc'] = 1
#         result['failed'] = True
#         error_string = "%s(%s)" % (e.__class__.__name__, e)
#         result['msg'] = u"Error %s reading %s" % (error_string, secret_path)
#         return result
#     if not response:
#         if default is not None:
#             result['value'] = default
#             return result
#         result['rc'] = 1
#         result['failed'] = True
#         result['msg'] = u"Secret %s is not in vault" % secret_path
#         return result
#     if version == 2:
#         try:
#             data = response.get('data', {})
#             metadata = data.get('metadata', {})
#             data = data.get('data', {})
#         except Exception:
#             data = str(response)
#     else:
#         data = response['data']
#         metadata = {}
#     lease_duration = response.get('lease_duration', None)
#     if lease_duration is not None:
#         result['lease_duration'] = lease_duration
#     lease_id = response.get('lease_id', None)
#     if lease_id is not None:
#         result['lease_id'] = lease_id
#     renewable = response.get('renewable', None)
#     if renewable is not None:
#         result['renewable'] = renewable
#     wrap_info = response.get('wrap_info', None)
#     if wrap_info is not None:
#         result['wrap_info'] = wrap_info
#     if key and key not in data:
#         if default is not None:
#             result['value'] = default
#             return result
#         result['rc'] = 1
#         result['failed'] = True
#         result['msg'] = u"Key %s is not in secret %s" % (key, secret_path)
#         return result
#     if key:
#         value = data[key]
#     else:
#         value = data
#     result['value'] = value
#     result['metadata'] = metadata
#     return result


# Path: ansible/plugins/lookup/hashivault.py
import os
import sys
from ansible.errors import AnsibleError
from ansible.module_utils.basic import AnsibleFallbackNotFound
from ansible.plugins.lookup import LookupBase
from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_read





class LookupModule(LookupBase):

    def _get_params(self, argspec, terms, kwargs):
        params = {}
        for arg in argspec:
            spec = argspec[arg]
            if arg in kwargs:
                params[arg] = kwargs[arg]
            elif 'default' in spec:
                params[arg] = spec.get('default')
            elif 'fallback' in spec:
                fall_func, fall_args = spec.get('fallback')
                try:
                    params[arg] = fall_func(*tuple(fall_args))
                except AnsibleFallbackNotFound:
                    pass

        params['secret'] = terms[0]
        try:
            params['key'] = terms[1]
        except IndexError:
            params['key'] = None
        return params

    def run(self, terms, variables=None, **kwargs):
        # self._display.v('Running lookup')

        argspec = hashivault_argspec()