#!/usr/bin/env python
#
# Utility for managing a database of references, typically a list of
# papers and presentations organized in different categories. The
# database is maintained in an easy-to-read and easy-to-edit format
# (emacs org-format). Using this script, lists of references can be
# filtered (for example, to include only peer-reviewed papers, only
# presentations etc) and output in one of many formats (BibTeX, HTML
# and others).

from __future__ import print_function
__author__ = "Anna Logg (anna@loggsystems.se)"
__date__ = "2008-09-24 -- 2008-12-12"
__copyright__ = "Copyright (C) 2008 Anna Logg"
__license__  = "GNU GPL version 3 or any later version"

# Modified by Anders Logg, 2009.

import sys

from publish.importing import import_file
from publish.exporting import export_file
from publish.validation import validate_file
from publish.printing import print_file
from publish.log import error
from publish import config

PUBLISH_VERSION = "1.0"

def extract_options(args):
    "Extract command options"

    filters = {}
    newargs = []

    for arg in args:
        if "!=" in arg:
            words = arg.split("!=")
            if not len(words) == 2:
                raise RuntimeError("Illegal option: %s" % arg)
            key, value = words
            filters[key] = (value, False)
        elif "=" in arg:
            words = arg.split("=")
            if not len(words) == 2:
                raise RuntimeError("Illegal option: %s" % arg)
            key, value = words
            if config.has_key(key) :
                config.set_from_string(key, value)
            else:
                filters[key] = (value, True)
        else:
            newargs.append(arg)

    return newargs, filters

def print_usage():
    "Print help text"
    print("""\
Usage: publish <command> [command/global option]... [filename]

Commands: import, validate, export, print

For more information, refer to the Publish man page ('man publish')
or the Publish User Manual.
""")
    print_copyright()

def print_copyright():
    "Print copyright notice"
    print("""\
Copyright (C) 2008 Anna Logg (Logg Systems).
Licensed under the GNU GPL version 3 or any later version.""")

def print_version():
    "Print version number"
    print("This is Publish, a distributed publication management system, version %s." % PUBLISH_VERSION)
    print("")
    print_copyright()

def run_import(args, filters):
    "Run import command"
    for filename in args:
        import_file(filename, filters)

def run_export(args, filters):
    "Run export command"
    for filename in args:
        export_file(filename, filters)

def run_validate(args, filters):
    "Run validate command"
    if len(args) > 0:
        for filename in args:
            validate_file(filename)
    else:
        validate_file(None)

def run_print(args, filters):
    "Run print command"
    print_file(filters)

# Available commands
commands = {"import":   run_import,
            "export":   run_export,
            "validate": run_validate,
            "print":    run_print}

def main(args):

    # Print help text if requested
    if len(args) == 1 and args[0] in ("-h", "--help"):
        print_usage()
        return 0

    # Print version number if requested
    if len(args) == 1 and args[0] in ("-v", "--version"):
        print_version()
        return 0

    # Check command
    if len(args) >= 1 and args[0] in commands:

        # Choose command
        command = commands[args[0]]

        # Extract options
        args, filters = extract_options(args[1:])

        # Run command if running in debug mode
        if config.get("debug"):
            return command(args, filters)

        # Run command and catch exception if not in debug mode
        if 1:
            return command(args, filters)
        try:
            return command(args, filters)
        except Exception as message:
            error(message)
            return 2
    # Illegal arguments
    print_usage()
    return 2

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
