#!/usr/bin/env python
"""The Planet aggregator.

A flexible and easy-to-use aggregator for generating websites.

Visit http://www.planetplanet.org/ for more information and to download
the latest version.

Requires Python 2.1, recommends 2.3.
"""

__authors__ = [ "Scott James Remnant <scott@netsplit.com>",
                "Jeff Waugh <jdub@perkypants.org>" ]
__license__ = "Python"

import os, shutil, sys
from os import path

DEFAULT_CONFIGURATION_FILE_NAME = "/usr/share/planet-venus/example/default.ini"
DEFAULT_THEME_DIRECTORY_NAME = "/usr/share/planet-venus/theme/default"

if __name__ == "__main__":
    config_file = "config.ini"
    offline = 0
    verbose = 0
    debug = 0
    only_if_new = 0
    expunge = 0

    def display_error(message):
        print >> sys.stderr, message
        print >> sys.stderr
        print >> sys.stderr, "Try `planet --help' for more information."
        sys.exit(1)

    for key, arg in enumerate(sys.argv[1:]):
        if arg == "-h" or arg == "--help":
            print """Usage: planet [OPTION]... [CONFIGURATION-FILE]

Planet Venus downloads news feeds published by web sites and aggregates their
content together into a single combined feed, latest news first.

The exit status is 0 for success or 1 for failure.

Options:

  -h, --help              display a short help message and exit
  -V, --version           display version information and exit
  -v, --verbose           verbose logging during update
  -d, --debug             debug logging during update
  -o, --offline           update from the cache only
  -n, --only-if-new       only spider new feeds
  -x, --expunge           expunge old entries from cache
  -c, --create=DIRECTORY  create a new planet in DIRECTORY

Examples:

You can create a default planet:

  planet --create example

You can build this default planet right away:

  cd example && planet --verbose planet.ini

You can test the results in your favourite browser:

  sensible-browser output/index.html

The configuration file has more details for customisation:

  sensible-editor planet.ini

Report bugs using the `reportbug' command."""
            sys.exit(0)
        elif arg == "-V" or arg == "--version":
            print """planet - Planet Venus "0~bzr116"

Copyright 2008, Sam Ruby <rubys@intertwingly.net>

Licenced under the Python Software Foundation License Version 2.

Written by Sam Ruby <rubys@intertwingly.net>."""
            sys.exit(0)
        elif arg == "-c" or arg == "--create":
            planet_directory_name = sys.argv[key + 2]
            configuration_file_name = path.join(planet_directory_name, "planet.ini")
            theme_directory_name = path.join(planet_directory_name, "theme")
            if not path.exists(planet_directory_name):
                os.makedirs(planet_directory_name)
            if not path.exists(configuration_file_name):
                shutil.copy(DEFAULT_CONFIGURATION_FILE_NAME, configuration_file_name)
            if not path.exists(theme_directory_name):
                shutil.copytree(DEFAULT_THEME_DIRECTORY_NAME, theme_directory_name)
            sys.exit(0)
        elif arg == "-v" or arg == "--verbose":
            verbose = 1
        elif arg == "-d" or arg == "--debug":
            debug = 1
        elif arg == "-o" or arg == "--offline":
            offline = 1
        elif arg == "-n" or arg == "--only-if-new":
            only_if_new = 1
        elif arg == "-x" or arg == "--expunge":
            expunge = 1
        elif arg.startswith("-"):
            display_error("Unknown option: %s" % arg)
        else:
            config_file = arg

    if not config_file:
        display_error("No configuration file specified.")

    if not path.exists(config_file):
        display_error("The configuration file does not exist: %s" % config_file)

    from planet import config
    config.load(config_file)

    import planet

    if debug:
        planet.getLogger('DEBUG',config.log_format())
    elif verbose:
        planet.getLogger('INFO',config.log_format())
    else:
        planet.getLogger('WARNING',config.log_format())

    if not offline:
        from planet import spider
        try:
            spider.spiderPlanet(only_if_new=only_if_new)
        except Exception, e:
            print e

    from planet import splice
    doc = splice.splice()
    splice.apply(doc.toxml('utf-8'))

    if expunge:
        from planet import expunge
        expunge.expungeCache
