"""Migrate CMFSites named on command line.

This script is inteneded to be run via 'zopectl run'.

Usage:

  bin/zopectl run Products/CMFCore/scripts/migrate_21.py [options] path [path*]

where each 'path' is a slash-delimited physical path to a CMFSite.

Options include

  -q, --quiet     quiet (no console output, unless errors)
  -n, --dry-run   do all the work, but abort the transaction
  -h, --help      get help on options (this screen)
"""
import getopt
import sys
import transaction

from Products.CMFCore.interfaces import ISiteRoot

def _note(msg):
    print msg

def _ignore(msg):
    pass

global logger
logger = _note

def migrate(site_path):
    logger('Resolving path: %s' % site_path)
    site = app.unrestrictedTraverse(site_path)

    if not ISiteRoot.providedBy(site):
        raise ValueError('Not a CMF site: %s' % site_path)
    logger('Found site: %s' % site_path)

    #XXX:  now whack it to make it a new thing .e.g.:

    # logger('Stamping site with IObjectSiteManager')
    # directlyProvides(site, IObjectSiteManager)

    # logger('Creating local site registry')
    # site.doWhateverToCreteLocalComponentRegistry

    # logger('Running import step to mark tools as utilities')
    # site.portal_setup.setImportContext('whatever')
    # site.portal_setup.runImportStep('tool_utilities', False)


if __name__ == '__main__':

    dry_run = False

    short_args = "qnh"
    long_args = ["quiet",
                 "dry-run",
                 "help",
                ]
    try:
        opts, args = getopt.getopt(sys.argv[1:], short_args, long_args)
    except getopt.GetoptError:
        print __doc__
        sys.exit(1)

    for option, value in opts:

        if option in ("-h", "--help"):
            print __doc__
            sys.exit(2)

        if option in ("-q", "--quiet"):
            logger = _ignore

        if option in("-n", "--dry-run"):
            dry_run = True

    if len(args) == 0:
        print __doc__
        sys.exit(1)

    for site_path in args:
        migrate(site_path)

    if dry_run:
        logger('Aborting transaction.')
        transaction.abort()
    else:
        logger('Committing transaction.')
        transaction.commit()
