# !/usr/bin/python

from ansible.module_utils.basic import *

DOCUMENTATION = '''
module: dcos_iam_group
short_description: Instrument DC/OS IAM (identity and access management)
description:
  - list details of groups in DC/OS IAM
  - create groups in DC/OS IAM
  - delete groups in DC/OS IAM
version_added: "1.0"
options:
  dcos_url:
    description:
      - DC/OS IAM API base url
    required: true
  user:
    description:
      - DC/OS user with superuser rights
    required: true
  password:
    description:
      - DC/OS user password
    required: true
  group:
    description:
      - name of the group to create (only lowercase letters!)
    required: true
  state:
    description:
      - Whether to list the group details or create a new group
    required: false
    default: view
    choices: [view, present, absent]
requirements: ['requests', 'json', 're']
notes:
 - Version 1.0
author: Timo Bartels <timo@bartels-online.net>
'''

EXAMPLES = '''
# Verify whether a group exists in DC/OS IAM
- pip: name=requests state=present
  become: yes

- dcos_iam_group:
    dcos_url: https://master-url
    user: dcos_admin
    password: dcos_admin_password
    group: the_group_requested
    state: view

# Create a group in DC/OS IAM
- pip: name=requests state=present
  become: yes

- dcos_iam_group:
    dcos_url: https://master-url
    user: dcos__admin
    password: dcos_admin_password
    group: the_group_requested
    state: present

# Delete a group in DC/OS IAM
- pip: name=requests state=present
  become: yes

- dcos_iam_group:
    dcos_url: https://master-url
    user: dcos_admin
    password: dcos_admin_password
    group: the_group_requested
    state: absent

'''

import requests
import json


def __err(msg, error):
  return "%s: %s (HTTP %s)"%(msg, error.response.json()["message"], str(error.response.status_code)) 

def __get_auth_token(dcos_url, user, password):
  url = "%s/acs/api/v1/auth/login"%dcos_url
  header = {'Content-Type': 'application/json'}
  auth_payload = {'uid': '%s'%user, 'password': '%s'%password}
  response = requests.post(url, data=json.dumps(auth_payload), headers=header) 
  response.raise_for_status()
  return response.json()['token']

def __get_group_details(dcos_url, group, token):
  url = "%s/acs/api/v1/groups/%s"%(dcos_url, group)
  header = {"Authorization": "token=%s" % token, 'Content-Type': 'application/json'}
  response = requests.get(url, verify=False, headers=header)
  if response.status_code == 400:
    return {'success': False, 'changed': False, 'message': 'DCOS error: %s' %response.json()['description'], 'status_code': '%s' %response.status_code }
  if response.status_code == 200:
    return { 'success': True, 'changed': False, 'message': '%s' %response.json(), 'status_code': '%s' %response.status_code }

def __create_group(dcos_url, group, token):
  url = "%s/acs/api/v1/groups/%s"%(dcos_url, group)
  header = {"Authorization": "token=%s" % token, 'Content-Type': 'application/json'}
  description={'description': 'auto generated by script'}
  response = requests.put(url, verify=False, json=description, headers=header)
  if response.status_code == 409:
    return {'success': True, 'changed': False, 'message': '%s' %response.json()['description'], 'status_code': '%s' %response.status_code }
  if response.status_code == 201:
    return { 'success': True, 'changed': True, 'message': 'Group %s successfully created.' %group, 'status_code': '%s' %response.status_code }

def __delete_group(dcos_url, group, token):
  url = "%s/acs/api/v1/groups/%s"%(dcos_url, group)
  header = {"Authorization": "token=%s" % token, 'Content-Type': 'application/json'}
  response = requests.delete(url, verify=False, headers=header)
  if response.status_code == 400:
    return {'success': False, 'changed': False, 'message': '%s' %response.json()['description'], 'status_code': '%s' %response.status_code }
  if response.status_code == 204:
    return { 'success': True, 'changed': True, 'message': 'Group %s successfully deleted.' %group, 'status_code': '%s' %response.status_code }




def __play(params):
  if params['group'] is None or not params['group'].islower():
    return {'success': False, 'changed': False, 'message': 'Group name is invalid! Make sure to only use lowercase letters and no underscores.'}
 
  token = None
  try:
    token = __get_auth_token(params['dcos_url'], params['user'], params['password'])
  except requests.exceptions.RequestException as err:
    return {'success': False, 'changed': False, 'message': 'Could not authenticate against DCOS IAM API'}

  if params['state'] == 'view':
    return __get_group_details(params['dcos_url'], params['group'], token)
  elif params['state'] == 'present':
    return __create_group(params['dcos_url'], params['group'], token)
  elif params['state'] == 'absent':
    return __delete_group(params['dcos_url'], params['group'], token)




def main():
    module = AnsibleModule(argument_spec=dict
                           (dcos_url=dict(required=True, type='str'),
                            user=dict(required=True, type='str'),
                            password=dict(required=True, type='str'),
                            group=dict(required=True, type='str'),
                            state=dict(required=False, type='str', choices=['view', 'present', 'absent'], default='view')),
                           supports_check_mode=False)

    result = __play(module.params)

    if not result['success']:
        module.fail_json(msg=result['message'])
    else:
        module.exit_json(changed=result['changed'], msg=result['message'])


if __name__ == '__main__':
    main()

