#!/usr/bin/env python2

import optparse, sys, string, random

from twisted.internet import reactor

from gitorious_mrq import ircbot

# TODO: an option to log/cache the retrieved files
# This allows to easily update the data files used for features tests.
# A allows post-mortem debugging in case of failures, and
# such data can be used as test-data for regression tests

if __name__ == "__main__":

    usage = '%prog [options] PROJECT'
    parser = optparse.OptionParser()

    parser.add_option('', "--host", default='http://gitorious.org',
                      help="The URL to the Gitorious instance hosting the project.")

    parser.add_option('', "--poll-interval", default=5*60, type='int',
                      help="The interval to poll the feed and look for updates (in seconds).")

    # Options for IRC
    parser.add_option('', "--irc-server", default='irc.freenode.net',
                      help="The server to connect IRC bot to.")
    parser.add_option('', "--irc-port", default=6667, type='int',
                      help="The port to use for IRC bot.")
    parser.add_option('', "--irc-channel", default='#$project',
                      help="The channel to join for IRC bot.")
    parser.add_option('', "--irc-nick", default='autogenerated',
                      help="The nick to use for IRC bot.")

    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.error('You must specify the project name')

    project = args[0]

    if options.irc_nick == 'autogenerated':
        options.irc_nick = 'mrqbot-%s' % ''.join([random.choice(string.hexdigits) for x in range(5)])

    if options.irc_channel == '#$project':
        options.irc_channel = "#%s" % project

    f = ircbot.IrcBotFactory(options.irc_channel, options.irc_nick, options.host, project, options.poll_interval)
    reactor.connectTCP(options.irc_server, options.irc_port, f)
    reactor.run()
