#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    @copyright: 2008-2012 Lari Huttunen
    @license: MIT <http://www.opensource.org/licenses/mit-license.php>
"""
import re
import sys
import socket
import optparse
from opencollab.meta import Metas
from opencollab.util.regexp import *
from opencollab.util.wiki import importMetas
from opencollab.util.config import parseOptions
from opencollab.wiki import CLIWiki, WikiFailure


def main():
    parser = optparse.OptionParser()
    parser.add_option("-m", "--meta-name",
        dest="metakey", default=None, metavar="META",
        help=("META key whose value used for object instantiation."))
    parser.add_option("-y", "--type",
        dest="type", default=None, metavar="TYPE",
        help=("Object TYPE to instantiate, e.g. TYPE=NAME."))
    parser.set_usage("%prog [options]")
    brackets = re.compile('[\[\]]')
    ops = {}
    failed = []
    collab_metas = Metas()
    sect = "instantiate-objects"
    ops = parseOptions(parser, sect, search=True, template=True)
    x509 = ops[sect]["x509"]
    x509_ca_file = ops[sect]["x509_ca_file"]
    verbose = ops[sect]["verbose"]
    template = ops[sect]["template"]
    if template is None:
        template = "IdentityTemplate"
    meta = ops[sect]["metakey"]
    if meta is None:
        parser.error("You need to specify the meta key to look for on the selected pages. Use -h for help.")
    search = ops[sect]["search"]
    if search is None:
        parser.error("You need to specify the MetaTable search string. Use -h for help.")
    type = ops[sect]["type"]
    if type is None:
        parser.error("You need to specify the object type for the new objects, i.e. NAME. Use -h for help.")
    while True:
        try:
            collab = CLIWiki(ssl_verify_cert=x509, ssl_ca_certs=x509_ca_file, **ops['creds'])
        except WikiFailure:
            print "ERROR: Authentication failed."
        except (UnicodeError, socket.gaierror):
            sys.exit("ERROR: Not a valid URL.")
        else:
            break
    if verbose:
        print "Fetching identities from collab."
    pages = collab.getMeta(search)
    for page in pages:
        for m in pages[page][meta]:
            m = brackets.sub('', m)
            collab_metas[m]["TYPE"].add(type)
    failed = importMetas(collab, collab_metas, template, verbose, False)
    if failed:
        for page in failed:
            if verbose:
                print "ERROR uploading:", page, repr(collab_metas[page])
            else:
                print "ERROR uploading:", page

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print "Script interrupted via CTRL-C."
