#!/usr/bin/env python3
'''
Central CaaS Ansible Module
'''
# MIT License
#
# Copyright (c) 2021 <NAME> (@mageo) - BNC Business Network Communications AG
# Copyright (c) 2020 <NAME>.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

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

ANSIBLE_METADATA = {
  'metadata_version': '1.0',
  'status': [
    'preview'
  ],
  'supported_by': 'community'
}

DOCUMENTATION = """
---
module: central_caas
version_added: 2.9.0
short_descriptions: REST module for CaaS API on Aruba Central
description: This module provides a mechanism to interact with the CaaS API to
             perform configuration-related actions on gateways. It is based on
             work from Michael Rose Jr. available at 
             https://github.com/michaelrosejr/arubacentralcaas/
options:
  action:
    description:
      - Action to be performed
      - "show_committed" gets committed configuration for a group or a device.
      - "upload_config" uploads configuration to Central.
    required: true
    type: str
    choices:
      - show_committed
      - upload_config
  group:
    description:
      - Name of group
    required: true
    type: str
  device:
    description:
      - Device's MAC address. Can be null to work with a group instead of a device.
    required: true
    type: str
"""

import json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.central_http import CentralApi


def show_committed (central_api, group, device):
  '''
  Returns committed configuration for a device.
  '''
  if group is not None:
    group_name = group
    if device is not None:
      group_name += "/" + device
    path = central_api.get_url(
      "/caasapi/v1/showcommand/object/committed",
      {
        "group_name": group_name
      }
    )
    headers = central_api.get_headers(False, "get")
    result = central_api.get(path=path, headers=headers)
    return result
  return {
    "resp": "Group name must be specified.",
    "code": 400
  }


def api_call(module):
  '''
  Uses playbook parameters to determine type of API request to be made
  '''
  central_api = CentralApi(module)
  action = module.params.get('action').lower()
  group = module.params.get('group')
  device = module.params.get('device')

  if action == "show_committed":
    result = show_committed(central_api, group, device)

  elif action == "upload_config":
    # ToDo: To implement
    result = {}

  else:
    module.fail_json(changed=False, msg="Unsupported action provided in playbook")

  return result


def main():
  '''
  Central devices-related parameter definitions and response handling for
  module
  '''
  module = AnsibleModule(
    argument_spec=dict(
      action=dict(
        required=True,
        type='str',
        choices=[
          'show_committed',
          'upload_config'
        ]
      ),
      group = dict(
        required=True,
        type="str"
      ),
      device = dict(
        required=True, 
        type='str'
      ),
    )
  )

  success_codes = [200, 201]
  exit_codes = [304, 400, 404]

  changed = False
  if "get" not in module.params.get('action').lower():
    changed = True

  result = api_call(module)

  try:
    result['resp'] = json.loads(result['resp'])
  except (TypeError, ValueError):
    pass

  # Trim ending white spaces
  trimmed_result = []
  for line in result['resp']['config']:
    trimmed_result.append(str(line).rstrip())
  result['resp']['config'] = trimmed_result
  
  if result['code'] and result['code'] in success_codes:
    module.exit_json(changed=changed, msg=result['resp'], response_code=result['code'])
  elif result['code'] and result['code'] in exit_codes:
    module.exit_json(changed=False, msg=result['resp'], response_code=result['code'])
  else:
    module.fail_json(changed=False, msg=result['resp'], response_code=result['code'])


if __name__ == '__main__':
  main()

#!/usr/bin/env python3
'''
Central CaaS Ansible Module
'''
# MIT License
#
# Copyright (c) 2021 <NAME> (@mageo) - BNC Business Network Communications AG
# Copyright (c) 2020 <NAME>.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

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

ANSIBLE_METADATA = {
  'metadata_version': '1.0',
  'status': [
    'preview'
  ],
  'supported_by': 'community'
}

DOCUMENTATION = """
---
module: central_caas
version_added: 2.9.0
short_descriptions: REST module for CaaS API on Aruba Central
description: This module provides a mechanism to interact with the CaaS API to
             perform configuration-related actions on gateways. It is based on
             work from Michael Rose Jr. available at 
             https://github.com/michaelrosejr/arubacentralcaas/
options:
  action:
    description:
      - Action to be performed
      - "show_committed" gets committed configuration for a group or a device.
      - "upload_config" uploads configuration to Central.
    required: true
    type: str
    choices:
      - show_committed
      - upload_config
  group:
    description:
      - Name of group
    required: true
    type: str
  device:
    description:
      - Device's MAC address. Can be null to work with a group instead of a device.
    required: true
    type: str
"""

import json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.central_http import CentralApi


def show_committed (central_api, group, device):
  '''
  Returns committed configuration for a device.
  '''
  if group is not None:
    group_name = group
    if device is not None:
      group_name += "/" + device
    path = central_api.get_url(
      "/caasapi/v1/showcommand/object/committed",
      {
        "group_name": group_name
      }
    )
    headers = central_api.get_headers(False, "get")
    result = central_api.get(path=path, headers=headers)
    return result
  return {
    "resp": "Group name must be specified.",
    "code": 400
  }


def api_call(module):
  '''
  Uses playbook parameters to determine type of API request to be made
  '''
  central_api = CentralApi(module)
  action = module.params.get('action').lower()
  group = module.params.get('group')
  device = module.params.get('device')

  if action == "show_committed":
    result = show_committed(central_api, group, device)

  elif action == "upload_config":
    # ToDo: To implement
    result = {}

  else:
    module.fail_json(changed=False, msg="Unsupported action provided in playbook")

  return result


def main():
  '''
  Central devices-related parameter definitions and response handling for
  module
  '''
  module = AnsibleModule(
    argument_spec=dict(
      action=dict(
        required=True,
        type='str',
        choices=[
          'show_committed',
          'upload_config'
        ]
      ),
      group = dict(
        required=True,
        type="str"
      ),
      device = dict(
        required=True, 
        type='str'
      ),
    )
  )

  success_codes = [200, 201]
  exit_codes = [304, 400, 404]

  changed = False
  if "get" not in module.params.get('action').lower():
    changed = True

  result = api_call(module)

  try:
    result['resp'] = json.loads(result['resp'])
  except (TypeError, ValueError):
    pass

  # Trim ending white spaces
  trimmed_result = []
  for line in result['resp']['config']:
    trimmed_result.append(str(line).rstrip())
  result['resp']['config'] = trimmed_result
  
  if result['code'] and result['code'] in success_codes:
    module.exit_json(changed=changed, msg=result['resp'], response_code=result['code'])
  elif result['code'] and result['code'] in exit_codes:
    module.exit_json(changed=False, msg=result['resp'], response_code=result['code'])
  else:
    module.fail_json(changed=False, msg=result['resp'], response_code=result['code'])


if __name__ == '__main__':
  main()

#!/usr/bin/env python3 Central CaaS Ansible Module # MIT License # # Copyright (c) 2021 <NAME> (@mageo) - BNC Business Network Communications AG # Copyright (c) 2020 <NAME>. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. --- module: central_caas version_added: 2.9.0 short_descriptions: REST module for CaaS API on Aruba Central description: This module provides a mechanism to interact with the CaaS API to              perform configuration-related actions on gateways. It is based on              work from Michael Rose Jr. available at               https://github.com/michaelrosejr/arubacentralcaas/ options:   action:     description:       - Action to be performed       - "show_committed" gets committed configuration for a group or a device.       - "upload_config" uploads configuration to Central.     required: true     type: str     choices:       - show_committed       - upload_config   group:     description:       - Name of group     required: true     type: str   device:     description:       - Device's MAC address. Can be null to work with a group instead of a device.     required: true     type: str Returns committed configuration for a device. Uses playbook parameters to determine type of API request to be made # ToDo: To implement Central devices-related parameter definitions and response handling for   module # Trim ending white spaces