#!/usr/bin/env python

import os
import sys
import Utils
import twitter

authfile = "/home/bortzmeyer/.twitter/auth"
blogdir = "/home/bortzmeyer/Blog"
sections = {"RFC": "rfc", "entries": "entry", "ficheslec": "fiche"}
max_twitter = 140
baseurl = "http://www.bortzmeyer.org" # Do not add a slash at the end

if len(sys.argv) != 2:
    print >>sys.stderr, ("Usage: %s file" % sys.argv[0])
    sys.exit(1)

if not os.path.exists(authfile):
    print >>sys.stderr, ("Cannot find %s" % authfile)
    sys.exit(1)

file = sys.argv[1]
for section in sections.keys():
    filepath = "%s/%s/%s.%s_xml" % (blogdir, section, file, sections[section])
    if not os.path.exists(filepath):
        filepath = None
    else:
        break
if filepath is None:
    print >>sys.stderr, ("Cannot find %s in %s" % (file, sections.keys()))
    sys.exit(1)
    
auth = open(authfile)
login = auth.readline()[:-1]
passwd = auth.readline()[:-1]
api = twitter.Api(username=login, password=passwd)
url = "%s/%s.html" % (baseurl, file)
title = unicode(Utils.title_of(Utils.file2DOM(filepath)), encoding="UTF-8")
rest = max_twitter - len(url) + 1
if len(title) > rest:
    shorttitle = title[:rest-3] + "..."
else:
    shorttitle = title
message = u"%s %s" % (shorttitle, url)
print message
status = api.PostUpdate(message)
print status
