#!/usr/bin/python
####################################################################################
#
# self_registrar
#
# Self_registrar is a part of Nagios automatic hosts self-registration software.
# NAR for simplicity.
# For detailer NAR description read README file.
#
# Usage:
#   Create a passively checked service "Nagios autoregister" for queue registrar.
#   See example provided in NAR package. Add event handler for this service.
#   Assign service to Nagios main host. Event handler takes command line parameters:
#     first - $SERVICESTATE$
#     second - $SERVICEOUTPUT$
#   Where $SERVICESTATE$ is service state - OK, CRITICAL, WARNING, UNKNOWN)
#         $SERVICEOUTPUT$ is a message sent by a remote host.
#   Message includes, separated by space:
#     command - "add", "remove", "register", "deregister"
#     host name to add to Nagios - FQDN or IP
#     host group names to add to, separated by comma
#     templates names to us, separated by comma
#   For example:
#     add proxmox.office.axian.ru proxmox-servers generic-host,debian-servers
#   If $SERVICESTATE$ is WARNING, script sends message ($SERVICEOUTPUT$) to a task queue
#
# Requirements:
#   Pyhon package - beanstalkc. The rest are IMHO standard in Ubuntu/Debian
#   Nagios V3 - is up and running on the same computer
#   Beanstalkd - tasks queue manager should be installed and running prior Nagios-AR
#      starts.
#
# (C) 2016 Andrey A. Porodko <andrey.porodko@gmail.com>
# (C) 2016 Axian Ltd, http://axian.ru
#
# v0.1 - initial release
#
####################################################################################

import sys, beanstalkc, string

if len(sys.argv) > 2:
    state = string.lower(sys.argv[1])
    if state == 'warning':
	try:
	    beanstalk = beanstalkc.Connection(host='localhost', port=11300)
	    beanstalk.use('nagios')
	    for i in range(2,len(sys.argv)):
		beanstalk.put(sys.argv[i])
	except Exception, e:
	    print 'Unable to queue a message', sys.argv[1:]
sys.exit(0)
