"""Routines that provide information and modify the state of various services on all nodes.

This exports:
  service_action - Used to start/stop/restart services on various nodes.
  get_service_status - Get the status of services from various nodes.

"""

import salt.client

# Global Declaration of services so as to reused everywhere else
default_services = {'Gluster': 'glusterd', 'CIFS-CTDB': 'ctdb',
                    'CIFS-Smb': 'smb', 'CIFS-Winbind': 'winbind', 'NTP': 'ntpd', 'NFS': 'rpcbind'}


def service_action(node, service, action):
    """Performs a action(start/stop/reload/restart on a service. 
      node - Either * or an individual node name. As per salt key names. It also accepts a list of node names as per saltstack definations
      service - accepts a service name defined in the default_services variable. Any function calling this, should import the default_services dict and pass the actual service name or just pass the service name of the service to be performed an action.
      action - status,restart,start,stop,reload. Accepts all these

    """
    if not service or not action:
        return False, "Service name or action not specified."
    try:
        # print 'a'
        # print service
        action = 'service.' + action
        # print action
        client = salt.client.LocalClient()
        status = client.cmd(node, action, [service])
        # print status
        if not status:
            return False, "Unknown Error"
        return status, None
    except Exception, e:
        return False, e


def get_services_status(services=default_services):
    """ Calls the service_action to get the status of all the services on all the nodes defined in the default_services.
    """
    try:
        service_status = {}
        client = salt.client.LocalClient()
        for name, service in services.items():
            status, err = service_action('*', service, 'status')
            if err:
                return False, "Unable to get status of %s(%s)" % (name, service)
            status, err = service_action('*', service, 'status')
            print status, err
            service_status[name] = status
        return service_status, None
    except Exception, e:
        return False, e


# print get_service_status()
# print service_action('*',['ntpd', 'glusterd'],'status')

# vim: tabstop=8 softtabstop=0 expandtab ai shiftwidth=4 smarttab
