#!/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)

import gopherfeed

import codecs
import getopt
import sys

def usage():
    """Print usage information."""
    print("""Usage pattern 1: gopherfeed FEED_URL [GOPHERMAP_FILENAME]
    This will turn the feed at FEED_URL into a Gophermp and save it to GOPHER_FILENAME
    if specified or print it stdout if not.
    
    Usage pattern 2: gopherfeed -f FEED_FILE -d GOPHER_DIR -h HOSTNAME
    This will read feed URLs from FEED_FILE (one URL per line) and turn them all into
    Gophermap files.  Each feed's Gophermap will end up in its own directory under
    the directory GOPHER_DIR.  A master Goperhmap pointing to each of the feeds will
    also be created under GOPHER_DIR, using the hostname HOSTNAME.""")

def main():
    feedfile = None
    directory = None
    hostname = None

    opts, args = getopt.gnu_getopt(sys.argv[1:], "d:f:h:")
    for option, value in opts:
        if option == "-d":
            directory = value
        elif option == "-f":
            feedfile = value
        elif option == "-h":
            hostname = value

    if feedfile and directory and hostname:
        try:
            gopherfeed.gopherize_feed_file(feedfile, directory, hostname, port=70)
        except IOError as e:
            print("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)
        if len(args) == 2:
            filename = args[1]
            try:
                fp = codecs.open(filename, "w", "UTF-8")
                fp.write(gophermap)
            except IOError as e:
                print("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()
