#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# pynag - Python Nagios plug-in and configuration environment
# Copyright (C) 2010 Pall Sigurdsson
# 
# This program 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 2 of the License, or
# (at your option) any later version.
# 
# This program 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 program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.



from pynag import Model
import os.path
from sys import argv,exit
import sys

def show_help():
	print """
%s - A Convenience script to add new service checks to nagios

USAGE:
	%s [OPTIONS] [attribute1=value1] [attribute2=value2]

OPTIONS:
	--quiet		not verbose (default false)
	--verbose	Verbose mode (default true)
	--filename	Filename to edit (default ${hostname}-custom.cfg)
	--config	Nagios main configuration file (default %s)
	attribute=value	set a speficic attribute to a new value

EXAMPLES:
	# %s  host_name=localhost use=generic-service service_description="custom nrpe" check_command='check_nrpe!custom'

	""" % (sys.argv[0], sys.argv[0], filename, sys.argv[0] )


verbose = True
attributes = {}
nagios_config = None
arguments = argv[1:]
filename = None

if len(arguments) == 0:
	print "No arguments provided"
	show_help()
	sys.exit(1)
while len(arguments) > 0:
	i = arguments.pop(0)
	if i == "--quiet":
		verbose = False
	elif i == '--verbose':
		verbose == True
	elif i == '--help':
		show_help()
		sys.exit(0)
	elif i == '-h':
		show_help()
		sys.exit(0)
	elif i == "--filename":
		filename=arguments.pop(0)	
	elif i == "--config":
		Model.cfg_file=arguments.pop(0)	
	elif i.find('=') > 1:
		key,value = i.split('=',1)
		attributes[key] = value
	else:
		print "Error: Dont know what to do with argument '%s'. " % i
		show_help()
		sys.exit(1)


if not attributes.has_key('host_name'):
	print "Error: host_name is required."
	sys.exit(1)

host_name = attributes['host_name']
try:
	host = Model.Host.objects.get_by_shortname(host_name)
except ValueError:
	print "Error: Host named '%s' not found. " % host_name
	sys.exit(1)

if filename is None:
	dirname = os.path.dirname( host._meta['filename'] )
	filename = '%s/%s-custom.cfg' % (dirname, host_name)

service = Model.Service()
service.set_filename(filename)
service.is_new = True

for k,v in attributes.items():
	service[k] = v


service.save()
if verbose:
	print "----------"
	print service
	print "----------"
	print "New service saved to %s" % (filename)
