#!/usr/bin/env python
###############################################################################
# (c) Copyright 2013 CERN                                                     #
#                                                                             #
# This software is distributed under the terms of the GNU General Public      #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING".   #
#                                                                             #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization  #
# or submit itself to any jurisdiction.                                       #
###############################################################################
import sys
import logging
from LbNightlyTools.Scripts.Common import PlainScript
from LbNightlyTools.Configuration import loadConfig


CONF_ZIP_URL = ('https://gitlab.cern.ch/lhcb-core/LHCbNightlyConf/'
                'repository/archive.zip?ref={0}')


def getSlotsFromGit(branch='master'):
    '''
    Helper to get the list of slots defined on the repository.
    '''
    from LbNightlyTools.Utils import TemporaryDir
    from urllib import urlretrieve
    from zipfile import ZipFile
    import os
    with TemporaryDir(chdir=True):
        url = CONF_ZIP_URL.format(branch)
        logging.debug('getting config files from %s', url)
        urlretrieve(url, 'config.zip')
        logging.debug('unpacking')
        z = ZipFile('config.zip')
        z.extractall()
        return loadConfig(z.namelist()[0])


class Script(PlainScript):
    '''
    Simple script to get the list of slots by deployment key.
    '''
    __usage__ = '%prog [options] deployment_type ...'

    def defineOpts(self):
        '''
        Prepare the option parser.
        '''
        self.parser.add_option('--branch',
                               help='branch of the configuration to use '
                                    '[default: %default]')
        self.parser.add_option('--configdir',
                               help='use configuration from the given '
                                    'directory instead of from gitlab')
        self.parser.set_defaults(branch='master')

    def main(self):
        deployments = set(map(str.lower, self.args))
        if not deployments:
            self.parser.error('you must specify at least one deployment type')
        slots = (loadConfig(self.options.configdir) if self.options.configdir
                 else getSlotsFromGit(self.options.branch))
        print('\n'.join(name for name, slot in sorted(slots.items())
                        if slot.enabled and
                            deployments.intersection(map(str.lower,
                                                         slot.deployment))))


if __name__ == '__main__':
    sys.exit(Script().run())
