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

# (c) 2013, Benno Joy <benno@ansibleworks.com>
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software.  If not, see <http://www.gnu.org/licenses/>.

DOCUMENTATION = '''
---
module: netscaler_bind
author: Benno Joy
short_description: Used to bind service to a vserver.
description:
 - Configure Citrix Netscaler's bindings, This module can be used to bind a service(endpoint) to a vserver(VIP), so that when a request arrives at the VIP it knows where to forward the requests to.

options:
  ns_host:
    description:
      - hostname or ip of your netscaler
    required: true
    default: null
    aliases: []
  user:
    description:
      - username of the Netscaler device
    required: true
    default: null
    aliases: []
  password:
    description:
      - password of the Netscaler user
    required: true
    default: null
    aliases: []
  service_name:
    description:
      - The name given to  the service.
    required: true
    default: null
    aliases: []
  state:
    description:
      - The state that should be applied on the entity.
    required: false
    default: absent
    choices: ["absent","present"]
    aliases: []
  vserver_name:
    description:
      - The name of the vserver(vip) to which this service to be binded to.
    required: true
    default: null
    aliases: []

examples: 

 - code: netscaler_bind "ns_host=172.16.101.2 user=nsroot password=nsroot service_name=abc vserver_name=myapp state=absent"
   description: "Adds a LB Vserver to Netscaler"

requirements: [ "nsnitro" ]

'''

try:
	from nsnitro import *
except:
	sys.exit(1)

class NetscaleBindService:
	
	def __init__(self,module):
			self.ns_host	       = module.params['ns_host']
			self.user	       = module.params['user']
			self.password	       = module.params['password']
			self.state             = module.params['state']
			self.service_name      = module.params['service_name']
			self.vserver_name      = module.params['vserver_name']
			self.mod	       = module
			self.change	       = True
			self.binding_available = False
			try:
				self.conn = NSNitro(self.ns_host,self.user,self.password)	
				self.conn.login()
			except:
				module.fail_json(msg = "Unable to login to Netscaler")
	
	def change_required(self):
		try:
			binding = NSLBVServerServiceBinding()
			binding.set_name(self.vserver_name)
			lbbindings = binding.get(self.conn,binding)
			for s in lbbindings:
				if s.get_servicename() == self.service_name:
				   self.binding_available = True
			if self.binding_available == True and self.state == 'present':
				self.change = False
			elif self.binding_available == False and self.state == 'absent':
				self.change = False

			return self.change
		except:
			self.mod.fail_json(msg = "Some issue in getting binding list from Netscaler")
				
		
	def add_binding(self):
		binding = NSLBVServerServiceBinding()
		binding.set_name(self.vserver_name)
		binding.set_servicename(self.service_name)
		try:
                	NSLBVServerServiceBinding.add(self.conn, binding)
		except:
			self.mod.fail_json(msg = "Error in adding binding to Netscaler")

	def delete_binding(self):
		binding = NSLBVServerServiceBinding()
		binding.set_name(self.vserver_name)
		binding.set_servicename(self.service_name)
		try:
                	NSLBVServerServiceBinding.delete(self.conn, binding)
		except:
			self.mod.fail_json(msg = "Error in deleting binding from Netscaler")
		
	
def main():
    
	module = AnsibleModule(
        argument_spec          = dict(
            ns_host            = dict(required=True),
            user               = dict(required=True),
            password           = dict(required=True),
            state      	       = dict(default='absent', choices=['absent','present']),
            service_name       = dict(required=True),
            vserver_name       = dict(required=True),
        )
    )

	binding = NetscaleBindService(module)
	if binding.change_required():
		if module.params['state'] == 'present':
			binding.add_binding()
			module.exit_json(changed=True,result="Success")
		else:
			binding.delete_binding()
			module.exit_json(changed=True,result="Success")
	module.exit_json(changed=False,result="Success")


# this is magic, see lib/ansible/module.params['common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main()
