from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

DOCUMENTATION = '''
        lookup: XTAM Vault
        author: Xton Technologies <info@xtontech.com>
        version_added: "1.3"
        short_description: retrieves sensitive values from XTAM Vault
        description:
            - This lookup retrieves sensitive values from XTAM Vault
        options:
          _terms:
            description: Record-ID Field
            required: True
        notes:
          - Connection parameters are configured using environment variables
          - ANS_XTAM_URL
          - ANS_XTAM_LOGIN
          - ANS_XTAM_PASSWORD
          - ANS_XTAM_TOKEN as an alternative to ANS_XTAM_LOGIN and ANS_XTAM_PASSWORD
          - Use export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES on latest Mac OS
          - Example of call lookup('xtam', 'i-4bbAmkj4QYq Password')
'''

import os
import requests
import json
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.plugins.lookup import LookupBase
from ansible.utils.display import Display

display = Display()

class XTAM(object):

    def __init__(self):
        self._xtam_url = os.environ.get('ANS_XTAM_URL')
        self._xtam_token = os.environ.get('ANS_XTAM_TOKEN')
        self._xtam_login = os.environ.get('ANS_XTAM_LOGIN')
        self._xtam_password = os.environ.get('ANS_XTAM_PASSWORD')

        if self._xtam_url is None:
            raise AnsibleError("Please provide XTAM URL in the environment variable ANSIBLE_XTAM_URL")

        if self._xtam_login is None and self._xtam_token is None:
            raise AnsibleError("Please provide XTAM Service Login in the environment variable ANSIBLE_XTAM_LOGIN or token in variable ANSIBLE_XTAM_TOKEN")

        if self._xtam_password is None and self._xtam_token is None:
            raise AnsibleError("Please provide XTAM Service Password in the environment variable ANSIBLE_XTAM_PASSWORD or token in variable ANSIBLE_XTAM_TOKEN")

    def get(self, id, field):
        unlockUrl = self._xtam_url + '/xtam/rest/record/unlock/' + id
        display.vvv(u"Unlock URL %s" % unlockUrl)

        if self._xtam_token is None:
            display.vvv(u"Basic authentication")
            r = requests.get(unlockUrl, auth=(self._xtam_login, self._xtam_password))
        else:
            display.vvv(u"Token authentication")
            cas = self._xtam_url + '/cas'
            url = self._xtam_url + '/xtam'
            token = self._xtam_token
            r = requests.get('{0}/login?service={1}/'.format(cas,url), headers={'token':token}, allow_redirects=False)
            location = r.headers['Location']
            r = requests.get(location, allow_redirects=False)
            jar = r.cookies
            r = requests.get(unlockUrl, cookies=jar)
            
        record = r.json()
        custom = json.loads(record['custom'])
        out = custom[field]
        return out.strip()

class LookupModule(LookupBase):

    def run(self, terms, variables=None, **kwargs):
        xtam = XTAM()
        ret = []
        args = terms[0].split();
        id = args[0]
        field = args[1]
        
        ret.append(xtam.get(id, field))
        
        display.vvv(u"Accessing record %s" % id)
        return ret
