#!/usr/bin/python

#
# Simple command line tool for managing WordPress Post
# Author: Juanjo Escribano <juanjo.escribano@gmail.com>
# Version: 0.1 (beta)
# License: GPL v3
# Notes : by the moment it only supports "New Post" operation
#

import xmlrpclib
from datetime import datetime
import getopt
import sys

class Post:
    """
    This class will save the post info
    Private Attributes : 
        _post_title : the title of the post
        _post_description : the body of the post
        _post_date : date timestamp of the post (now())
    """
    _post_title = ""
    _post_description = ""
    _post_date = ""

    def __init__(self, post_title, post_description):
        """
        constructor of the class
        """
        self._post_title = post_title
        self._post_description = post_description
        actual_date = datetime.now()
        self._post_date = actual_date.year.__str__() + " " + actual_date.month.__str__() + " " + actual_date.day.__str__()

    def toStructure(self):
        """
        Creates an structure with the information. The elements of the struct
        are defined as elements of <item> element in RSS 2.0 (by the moment
        I don't support all of them
        """
        post_structure = {
                         "title" : self._post_title,
                         "description" : self._post_description,
                         "pubDate" : self._post_date
                         }
        return post_structure

def main():
    """
    Main funcion. Parse the parameters and do the job
    """

    user = ""
    passwd = ""
    server = ""
    title = ""
    post = ""
    options, args = getopt.getopt(sys.argv[1:], "", ["server=", "user=", "pass=", "title=", "post="])
    for opt,val in options:
        if opt == "--user":
            user = val
        elif opt == "--pass":
            passwd = val
        elif opt == "--title":
            title = val
        elif opt == "--post":
            post = val
        elif opt == "--server":
            server = val

    # user and server are not optative
    if user == "" or server == "":
        print "Syntax: " + sys.argv[0] + " <server=wordpress_addr> <user=username> [pass=password, title=title, post=text]"
        sys.exit(0)

    # init a xmlrpclib.Server object 
    server = xmlrpclib.Server(server + "/xmlrpc.php")
    # Create a Post Object with title and post. Then try to post it
    post = Post(title, post)
    try:
        res = server.metaWeblog.newPost("1", user, passwd, post.toStructure(), "1")
    except xmlrpclib.ProtocolError, err:
        print "Error conecting with server"
        sys.exit(-1)
    except xmlrpclib.Fault, err:
        print "Error :" + err.__str__()
        sys.exit(-1)
    except err:
        print "Error :" + err.__str__()
        sys.exit(-1)

    print "Post id: " + res

# Start here
if __name__ == "__main__":
    main()

