#!/usr/bin/python 
#
# This script may be used to ping different blog indexservers using XML-RPC.
# Run script with the argument -h for help.
#
# Author: Magnus Runesson <M dot Runesson at gmail dot com>
# License: GPL
#

import sys
import os
import getopt
import xmlrpclib 
import logging
import logging.handlers
import ConfigParser

def pingblog(blogName, blogURL, pingURL):
	blogping = xmlrpclib.ServerProxy(pingURL)
	try:
   		result=blogping.weblogUpdates.ping(blogName,blogURL)
		log.info("Pinging %s gave the result %s.", pingURL, result)
	except:
    		log.warning("Could not ping server: %s", pingURL)


def setparam(section,option,arg):
	if arg == None:
		if config.has_option(section,option):
			return config.get(section,option)
		else:
			print "Missing parameter" + section + option
			exit(2)
	else:	
		return arg

def usage():
	print "Blogping is can be used to ping blog indexes when you have \
entered a new blog entry."
	print "You can either set the parameters in a config file or using \
commandline arguments."
	print "The following parameters are accepted:"
	print "-h	Shows this text"
	print "-c file	Read an alternative config file."
	print "-n name	The name of the blog you want to send a ping for."
	print "-u URL	URL to the blog you want to send a ping for."
	print "-s URLs	URLs to the rpc-servers you want to ping. The URLs \
must be comma separated"
	print ""
	print "The configfile are read in the following order /etc/blogping, \
~/.blogping."
	print "Example of a configfile:"
	print "[blog]"
	print "name=The Blog example"
	print "URL=http://example.blogspot.com/"
	print "ping=http://rpc.twingly.com/,http://rpc.weblogs.com"


# Activat logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("blogping")
syslogh = logging.handlers.SysLogHandler("/dev/log")
syslogh.setLevel(logging.INFO)
log.addHandler(syslogh)
log.setLevel(logging.INFO)

# Read comand line arguments and config files.
conffile=['/etc/blogping', os.path.expanduser('~/.blogping')]

argBlogName=None
argBlogURL=None
argPingURLs=None
try:
	options,args=getopt.getopt(sys.argv[1:],'hc:n:u:s')
except getopt.GetoptError:
        # print help information and exit:
        usage()
        sys.exit(2)
for o, a in options:
        if o in ("-h"):
            usage()
            sys.exit()
        if o in ("-c"):
            conffile = a
        if o in ("-n"):
            argBlogName = a
        if o in ("-u"):
            argBlogURL = a
        if o in ("-s"):
            argPingURLs = a

config = ConfigParser.ConfigParser()
config.read(conffile)

blogName=setparam("blog","name",argBlogName)
blogURL=setparam("blog","URL",argBlogURL)
pingURLs=setparam("blog","ping",argPingURLs).split(",")

# Ping servers.
for pingURL in pingURLs:
	pingblog(blogName,blogURL,pingURL)
	

logging.shutdown()
