#!/usr/bin/env python
# Copyright (c) 2013, Luke Maurits <luke@maurits.id.au>
# Published under the terms of the BSD 3-Clause License
# (see LICENSE file or http://opensource.org/licenses/BSD-3-Clause)

"""Usage: gopherfeed FEED_URL [GOPHERMAP] [OPTIONS]
Convert RSS/Atom feed at FEED_URL to Gophermap file and save to GOPHERMAP if
specified, otherwise print to stdout

Or: gopherfeed -f FEED_FILE -d GOPHER_DIR [OPTIONS]
Read RSS/Atom feed URLs from FEED_FILE (one URL per line) and create a
directory structure of Gophermaps, including a central index, under GOPHER_DIR

Options for feed file (2nd usage pattern):

    -h HOSTNAME         Specify hostname to use in central index Gophermap
                            (defaults to FQDN of current machine)
    -p PORT             Specify port to use in central index Gophermap
                            (defaults to 70)
    -s SORT             Specify order in which feeds are listed in central
                            index.  Options are:
                                ALPHA - sort alphabetically by title
                                TIME - sort by time of most recent entry

Common options (1st and 2nd usage patterns):

    -t                  Timestamp feed entries in gophermap file

Note that in the 2nd pattern, gopherfeed should be run from within the
Goper server's root directory, as GOPHER_DIR will be created (if necessary) in
the current working directory.  Paths in the central index Gophermap will
begin with GOPHER_DIR, so if GOPHER_DIR is not in the Gopher root then the
server will not be able to find the individual feed directories.

Feed files should contain one URL, including scheme (e.g. http://), per line.
Blank lines and lines beginning with # will be ignored.

By invoking usage pattern 2 from an hourly cron job, you can use your Gopher
client as a basic feed aggregator.  This works best if you use a client which
also has seamless HTTP/HTML support (e.g. lynx).

Please report bugs to <luke@maurits.id.au> or at
<https://github.com/lmaurits/gopherfeed/issues>
"""

import gopherfeed

import codecs
import getopt
import sys

def usage():
    """Print usage information."""
    print(__doc__)

def main():
    feedfile = None
    directory = None
    hostname = None
    port = 70
    sort = None
    timestamp = False
    opts, args = getopt.gnu_getopt(sys.argv[1:], "d:f:h:p:s:t")
    for option, value in opts:
        if option == "-d":
            directory = value
        elif option == "-f":
            feedfile = value
        elif option == "-h":
            hostname = value
        elif option == "-p":
            port = int(value)
        elif option == "-s":
            sort = value
        elif option == "-t":
            timestamp = True

    if sort not in (None, "alpha", "time"):
        sys.stderr.write("Ignoring unknown sort option: %s\n" % sort)
        sort = None

    if feedfile and directory:
        try:
            gopherfeed.gopherize_feed_file(feedfile, directory, hostname,
                    port=port, sort=sort, timestamp=True)
        except IOError as e:
            sys.stderr.write("Encountered error handling feed file: %s" % e.strerror)
            exit(1)
    elif not feedfile and not directory and len(args) in (1, 2):
        feed_url = args[0]
        gophermap = gopherfeed.gopherize_feed(feed_url, timestamp=True)
        if len(args) == 2:
            filename = args[1]
            try:
                fp = codecs.open(filename, "w", "UTF-8")
                fp.write(gophermap)
            except IOError as e:
                sys.stderr.write("Could not write gophermap to file %s: %s" % (filename, e.strerror))
                exit(1)
            finally:
                fp.close()
        else:
            print(gophermap)
    else:
        usage()

    sys.exit(0)

if __name__ == "__main__":
    main()
