#!/usr/bin/python

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

class ElasticsearchILMPolicy:
  def __init__(self, api, name):
    self.api   = api
    self.name  = name

  def get_data(self):
    status_code, data = self.api.get('_ilm/policy/{}'.format(self.name))
    if status_code == 200:
      return data[self.name]
    else:
      return {}

  def create(self, phases):
    self.api.put(
      '_ilm/policy/{}'.format(self.name),
      { 'policy': { 'phases': phases } }
    )

  def dict_has_changed(self, new_data, old_data):
    for option, value in new_data.items():
      if not option in old_data:
        if value:
          return True

      elif type(value) is dict:
        if self.dict_has_changed(value, old_data[option]):
          return True

      elif type(value) is list:
        if not type(data[option]) is list:
          return True
        if old_data[option].sort() != value.sort():
          return True

      elif str(old_data[option]) != str(value):
        return True

    return False

  def has_changed(self, phases):
    old_data = self.get_data()
    if not old_data or self.dict_has_changed(phases, old_data['policy']['phases']):
      self.create(phases)
      return True

    return False
    
def main():
  fields = {
    'name':         { 'type': 'str',  'required': True },
    'phases':       { 'type': 'dict', 'default': {} },
    'api_url':      { 'type': 'str',  'default': 'http://127.0.0.1:9200' },
    'api_user':     { 'type': 'str',  'default': None },
    'api_password': { 'type': 'str',  'default': None, 'no_log': True },
  }
  module = AnsibleModule(argument_spec=fields)

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

  ilm = ElasticsearchILMPolicy(api, module.params['name'])
  changed = ilm.has_changed(module.params['phases'])

  module.exit_json(changed=changed)

if __name__ == '__main__':
  main()