#!/usr/bin/env python

"""
Utility executable for IPP Condor deployment
"""
import sys
import os
import logging
#optparse Deprecated in python 2.7. Will be replaced by argparse
from optparse import OptionParser 
from Deployment import Deployment

if __name__ == '__main__':
    if os.getenv('PYTHONPATH') is not None:
        print 'Error: Unset PYTHONPATH environment variable to run this program'
        sys.exit(1)
    USAGE = """usage: %prog [options] <ipp site definition file>

Deploy the Condor-IPP softwares
"""
    PARSER = OptionParser(usage = USAGE)
    PARSER.set_defaults(verbose=True)
    PARSER.add_option( '-v', action = 'store_true', 
                      dest = 'verbose',
                      help = 'Be verbose',
                      default = False)
    PARSER.add_option('-q', action='store_true', 
                      dest = 'quiet',
                      help = 'Be quiet',
                      default = False)
    (OPTIONS, ARGS) = PARSER.parse_args()    # ... the values are stored in options
    if len(ARGS) != 1:
        PARSER.print_help()
        sys.exit(1)
    IPP_SITE_FILE = ARGS[0]
    # Logging setup
    LOGGER = logging.getLogger('ippdor')
    FORMATTER = logging.Formatter('%(asctime)s | %(levelname)7s | %(message)s', 
                                  '%Y-%m-%dT%H:%M:%S')
    STDOUT = logging.StreamHandler(sys.stdout)
    STDOUT.setFormatter(FORMATTER)
    LOGGER.addHandler(STDOUT) 
    if OPTIONS.verbose:
        LOGGER.setLevel(logging.DEBUG)
        LOGGER.debug('Logging level set to DEBUG')
    elif OPTIONS.quiet:
        LOGGER.setLevel(logging.ERROR)
        LOGGER.info('Logging level set to ERROR')
    else:
        LOGGER.setLevel(logging.INFO)
    # Import IppSite definition
    LOGGER.info('Importing local site definitions')
    try:
        os.makedirs('.tmp_site')
    except OSError:
        LOGGER.warn('Existing .tmp_site directory')
    import shutil
    shutil.copy(IPP_SITE_FILE, '.tmp_site/IppSite.py')
    INITFILE = open('.tmp_site/__init__.py', 'w')
    INITFILE.close()
    sys.path.append('.tmp_site')
    from IppSite import IppSite

    # Deployment
    try:
        DEPLOYMENT = Deployment(IppSite.SVN_SOURCE_URL,
                                IppSite.TARGET_DIRECTORY,
                                IppSite.TARGET_BINARY_DIRECTORY)
        DEPLOYMENT.check()
        DEPLOYMENT.svn_export()
        DEPLOYMENT.generate()
        DEPLOYMENT.deploy()
        DEPLOYMENT.clean(doit = True)
    except Exception, e:
        LOGGER.info('Exception caught')
        DEPLOYMENT.clean(doit = False)
        LOGGER.error(e)
        import traceback
        traceback.print_exc()
    # Clean temporary site
    LOGGER.info('Cleaning temporary site definitions')
    os.remove('.tmp_site/IppSite.py')
    try:
        os.remove('.tmp_site/IppSite.pyc')
    except OSError:
        pass # Ignore if not compiled
    os.remove('.tmp_site/__init__.py')
    os.rmdir('.tmp_site')
