#!/usr/bin/python

from ansible.module_utils.basic import *
from ansible.module_utils.elasticsearch_api import *

class ElasticsearchUser:
  def __init__(self, api, name):
    self.api   = api
    self.name  = name
    self.exist = False
    self.data  = {}

  def get_data(self):
    status_code, data = self.api.get('_security/user/{}'.format(self.name))
    if status_code == 200:
      self.exist = True
      self.data  = data[self.name]

  def has_changed(self, roles):
    if roles.sort() != self.data['roles'].sort():
      return True

    return False

  def password_has_changed(self, password):
    return not self.api.check_password(self.name, password)

  def change_password(self, password):
    self.api.put(
      '_security/user/{}/_password'.format(self.name),
      { 'password': password }
    )
    
  def create(self, options):
    self.api.put(
      '_security/user/{}'.format(self.name),
      options
    )
    
def main():
  fields = {
    'name':         { 'type': 'str',  'required': True },
    'password':     { 'type': 'str',  'required': True },
    'roles':        { 'type': 'list', 'default': [] },
    'api_url':      { 'type': 'str',  'default': 'http://127.0.0.1:9200' },
    'api_user':     { 'type': 'str',  'default': None },
    'api_password': { 'type': 'str',  'default': None },
    'state':        { 'type': 'str',  'default': 'present', 'required': True, 'choice': ['absent', 'present'] },
  }
  module = AnsibleModule(argument_spec=fields)
  changed = False
  special_users = [
    'elastic', 'kibana', 'logstash_system',
    'beats_system', 'apm_system', 'remote_monitoring_user'
  ]

  options = {
    'roles':    module.params['roles'],
    'password': module.params['password'],
  }

  api = ElasticsearchApi(
    module.params['api_url'],
    module.params['api_user'],
    module.params['api_password']
  )

  user = ElasticsearchUser(
    api,
    module.params['name'],
  )
  user.get_data()

  if not module.params['name'] in special_users:
    if module.params['state'] == 'absent':
      if user.exist:
        user.delete()
        changed = True

      module.exit_json(changed=changed)

    if not user.exist or user.has_changed(module.params['roles']):
      user.create(options)
      changed = True

  if user.password_has_changed(module.params['password']):
    user.change_password(module.params['password'])
    changed = True

  module.exit_json(changed=changed)

if __name__ == '__main__':
  main()