#!/usr/bin/env python
import sys
import optparse
import storytracker
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)


p = optparse.OptionParser(
    description="Archive the HTML from the provided URLs",
    usage="storytracker-archive [URL]... [OPTIONS]",
)

p.add_option(
    "--do-not-verify",
    "-v",
    action="store_false",
    dest="verify",
    default=True,
    help="Skip verification that HTML is in the response's content-type header"
)

p.add_option(
    "--do-not-minify",
    "-m",
    action="store_false",
    dest="minify",
    default=True,
    help="Skip minification of HTML response"
)

p.add_option(
    "--do-not-extend-urls",
    "-e",
    action="store_false",
    dest="extend_urls",
    default=True,
    help="Do not extend relative urls discovered in the HTML response"
)

p.add_option(
    "--do-not-compress",
    "-c",
    action="store_false",
    dest="compress",
    default=True,
    help="Skip compression of the HTML response"
)

p.add_option(
    "--output-dir",
    "-d",
    action="store",
    type="string",
    dest="output_dir",
    default=None,
    help="Provide a directory for the archived data to be stored"
)

kwargs, args = p.parse_args()

for a in args:
    obj = storytracker.archive(a, **kwargs.__dict__)
    if not kwargs.output_dir and obj:
        if kwargs.compress:
            sys.stdout.write(obj.gzip)
        else:
            sys.stdout.write(obj.html.encode("utf-8"))
    elif kwargs.output_dir and obj:
        sys.stdout.write(obj.archive_path)
