#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (C) 2008, Mathieu PASQUET <mpa@makina-corpus.com> aka kiorky
# Copyright (C) 2008, Jeanmichel Francois <jmf@makina-corpus.com> aka toutpt
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

import sys
import logging
import transaction
import pdb

from Acquisition import aq_base
from optparse import OptionParser
from DateTime import DateTime
from common import connect, initLogging

initLogging()

logger = logging.getLogger("migration")
parser = OptionParser()
parser.add_option("-c",
                  action="store", dest="zopeconf", default="parts/guerir2-1/etc/zope.conf",
                  help="Zope.conf path")
parser.add_option("--all",
                  action="store_true", dest="all", default=False,
                  help="Launch all migrations")
parser.add_option("--commit",
                  action="store_true", dest="commit", default=False,
                  help="Commits the changes done on the database. default is False")
parser.add_option("--defaultprofile",
                  action="store_true", dest="defaultprofile", default=False,
                  help="apply the default profilee")
parser.add_option("--profile",
                  action="store", dest="profile", default="",
                  help="'dev','preprod','prod', 'mpa', 'makinanantes'  can be specify. profile is apply at the end of the script")
parser.add_option("--pdb",
                  action="store_true", dest="pdb", default=False,
                  help="Start on a pdb (even an ipython pdb:))")
parser.add_option("--recatalog",
                  action="store_true", dest="recatalog", default=False,
                  help="refresh my portal_catalog")


(options, args) = parser.parse_args()

def profile(plone, p="default"):
    """apply anticancer profile.
    p argument must be in ('default', 'dev', 'preprod', 'prod', 'mpa')
    """
    l = logging.getLogger('profile')
    setup_tool = plone.portal_setup
    old_context = setup_tool.getImportContextID()
    profile_toimport = "profile-Products.AntiCancerProfiles:anticancer_%s"%p
    l.info('apply profile: %s'%profile_toimport)
    setup_tool.setImportContext(profile_toimport)
    setup_tool.runAllImportSteps()
    setup_tool.setImportContext(old_context)
    l.info('profile applied')


def recatalog(plone):
    catalog = plone.portal_catalog
    #clear and rebuild
    catalog.refresh(clear=1)
    #or just reindex some indexes
    catalog.manage_reindexIndex(ids=['getId','created'])

def main():
    if not options.profile in ('', 'default', 'dev', 'preprod', 'prod', 'mpa', 'makinanantes'):
        parser.print_help()
        sys.exit(0)

    if not options.zopeconf:
        parser.print_help()
        sys.exit(0)

    else:
        plone, user = connect(options.zopeconf)
        del logging.root.handlers[1]
        lhandler = logging.FileHandler('migration.log')
        lhandler.setFormatter(logging.Formatter("%(asctime)s %(name)-1s %(levelname)-2s - %(message)s"))
        logging.root.addHandler(lhandler)

        if options.pdb:
            pdb.set_trace()

        if options.defaultprofile or options.all:
            profile(plone, p="default")

        if options.profile:
            profile(plone, p=options.profile)

        if options.recatalog or options.all:
            recatalog(plone)

        if options.commit:
            transaction.commit()
