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


def main():
    parser = optparse.OptionParser()
    parser.add_option("-n", "--dry-run",
        dest="dryrun", action="store_true",
        default=False, help="Show what would have been deleted.")
    parser.set_usage("%prog [options]")
    ops = {}
    sect = "delete"
    ops = parseOptions(parser, sect, search=True)
    url = ops["creds"]["url"]
    x509 = ops[sect]["x509"]
    x509_ca_file = ops[sect]["x509_ca_file"]
    verbose = ops[sect]["verbose"]
    dryrun = ops[sect]["dryrun"]
    search_string = ops[sect]["search"]
    if search_string is None:
        parser.error("Search string needs to be specified. Use -h for help.")
    if verbose:
        print "Authenticating to: " + repr(url)
    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
    columns = re.compile('\|\|.*\|\|')
    if not columns.findall(search_string):
        search_string += ",||||"
    metas = collab.getMeta(search_string)
    for page in metas:
        print "Deleting %r..." % (page),
        if not dryrun:
            try:
                collab.deletePage(page)
                print "[ok].",
            except WikiFailure, (strerror):
                print "[failed]: %s" % (strerror),
        print
    print

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