#!/usr/bin/python
# -*- coding: utf-8 -*-

try:
    from linode import api as linode_api
    HAS_LINODE = True
except ImportError as ie:
    HAS_LINODE = False
    LINODE_IMPORT_ERROR = str(ie)


DOCUMENTATION = '''
---
module: linode_nodebalancer
short_description: Add / Delete / Update a linode nodebalancer
description:
    - Wrapper around the linode nodebalancer api https://www.linode.com/api/nodebalancer
version_added: "0.1"
author: Duncan Morris (@duncanmorris)
notes:
    - Other things consumers of your module should know
requirements:
    - list of required things
    - like the factor package
    - or a specic platform
options:
    name:
        required: true
        aliases: [ "node_id" ]
        description:
            - Name / NodeID of the nodebalancer to create, delete or update.
'''

EXAMPLES = '''

# Set the weight of node 'web01' to 0 on nodebalancer 'ambassador'
 - linode_nodebalancer: name=web01 weight=0 node=ambassador

'''


def nodebalancer_find(api, node_balancer_id, name):

    if node_balancer_id:
        return api.nodebalancer_list(NodeBalancerID=node_balancer_id)

    if name:
        nodebalancers = api.nodebalancer_list()
        for nb in nodebalancers:
            if nb['LABEL'] == name:
                return nb

    return None


def linodeNodeBalancers(module, api, state, name, node_balancer_id,
                        datacenter_id, paymentterm):

    debug = {}
    changed = False

    nodebalancer = nodebalancer_find(api, node_balancer_id, name)
    if nodebalancer:
        if state == "present":
            pass
        elif state == "absent":
            api.nodebalancer_delete(
                NodeBalancerId=nodebalancer['NODEBALANCERID']
            )
            nodebalancer = None
            changed = True

    else:
        if state == "present":
            api.nodebalancer_create(DatacenterID=datacenter_id,
                                    PaymentTerm=paymentterm,
                                    Label=name)
            changed = True

        elif state == "absent":
            pass

    module.exit_json(changed=changed, instances=nodebalancer, debug=debug)


# ===========================================
def main():
    module = AnsibleModule(
        argument_spec=dict(
            api_key=dict(required=False,
                         aliases=['linode_api_id'],
                         type='str'),
            name=dict(required=False,
                      type='str'),
            node_balancer_id=dict(required=False,
                                  type='int'),
            state=dict(required=False,
                       default='present',
                       choices=['present', 'absent'],
                       type='str'),
            datacenter_id=dict(required=False,
                               default=7,
                               type='int'),
            paymentterm=dict(required=False,
                             default=1,
                             type='int'),
        ),
        supports_check_mode=False
    )

    if not HAS_LINODE:
        module.fail_json(msg=LINODE_IMPORT_ERROR + " (pip install linode-python)")

    api_key = module.params.get('api_key')
    name = module.params.get('name')
    node_balancer_id = module.params.get('node_balancer_id')
    state = module.params.get('state')
    datacenter_id = module.params.get('datacenter_id')
    paymentterm = module.params.get('paymentterm')

    # Setup the api_key
    if not api_key:
        try:
            api_key = os.environ['LINODE_API_KEY']
        except KeyError, e:
            module.fail_json(msg='Unable to load %s' % e.message)

    # setup the auth
    try:
        api = linode_api.Api(api_key)
        api.test_echo()
    except Exception, e:
        module.fail_json(msg='%s' % e.value[0]['ERRORMESSAGE'])

    linodeNodeBalancers(module, api, state, name, node_balancer_id,
                        datacenter_id, paymentterm)


from ansible.module_utils.basic import *

if __name__ == '__main__':
    main()

@@ -1279,16 +1279,476 @@
  None%0A%0A%0A
+def handle_api_error(func):%0A    def handle(*args, **kwargs):%0A        try:%0A            return func(*args, **kwargs)%0A        except linode_api.ApiError as e:%0A            code = e.value%5B0%5D%5B'ERRORCODE'%5D%0A            err = e.value%5B0%5D%5B'ERRORMESSAGE'%5D%0A            msg = %22FATAL: Code %5B%7Bcode%7D%5D - %7Berr%7D%22.format(code=code,%0A                                                        err=err)%0A            return args%5B0%5D.fail_json(msg=msg)%0A    return handle%0A%0A%0A@handle_api_error%0A
 def lino
@@ -1861,26 +1861,33 @@
 term
-):%0A%0A    debug = %7B%7D
+, client_conn_throttle):%0A
 %0A   
@@ -2034,20 +2034,548 @@
         
-pass
+if nodebalancer%5B'LABEL'%5D != name or %5C%0A               nodebalancer%5B'CLIENTCONNTHROTTLE'%5D != client_conn_throttle:%0A%0A                new = api.nodebalancer_update(%0A                    NodeBalancerID=nodebalancer%5B'NODEBALANCERID'%5D,%0A                    Label=name,%0A                    ClientConnThrottle=client_conn_throttle)%0A                changed = True%0A                nodebalancer = nodebalancer_find(api,%0A                                                 new%5B'NodeBalancerID'%5D,%0A                                                 name)
 %0A       
@@ -3128,21 +3128,8 @@
 ncer
-, debug=debug
 )%0A%0A%0A
@@ -3982,17 +3982,248 @@
         
-)
+    client_conn_throttle=dict(required=False,%0A                                      default=0,%0A                                      type='int')%0A        ),%0A        required_one_of=%5B%0A            %5B'name', 'node_balancer_id'%5D%0A        %5D
 ,%0A      
@@ -4649,16 +4649,85 @@
 ntterm')
+%0A    client_conn_throttle = module.params.get('client_conn_throttle')
 %0A%0A    # 
@@ -5223,16 +5223,38 @@
 mentterm
+, client_conn_throttle
 )%0A%0A%0Afrom

Handle API errors, and write update nodebalancer for when it is present with different values