#!/usr/bin/env python
#
# Created as part of the StratusLab project (http://stratuslab.eu),
# co-funded by the European Commission under the Grant Agreement
# INFSO-RI-261552."
#
# Copyright (c) 2010, SixSq Sarl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import sys

sys.path.append('/var/lib/stratuslab/python')

from stratuslab.marketplace.Util import Util as MarketplaceUtil
from stratuslab.commandbase.CommandBase import CommandBaseSysadmin
from stratuslab.ConfigHolder import ConfigHolder
from stratuslab.marketplace.Policy import Policy

# initialize console logging
import stratuslab.api.LogUtil as LogUtil

LogUtil.get_console_logger()


class MainProgram(CommandBaseSysadmin):
    """A command-line program to check site policy to authorize a given machine to be instantiated."""

    def __init__(self):
        self.metadataFilename = None
        self.policyConfigFilename = None
        super(MainProgram, self).__init__()

    def parse(self):
        self.parser.usage = '%prog [options] image-identifier'

        self.parser.description = '''
Evaluate the machine image policy for the given Marketplace
identifier.
'''

        self.parser.add_option('--policy', dest='policyConfigFile',
                               help='Policy configuration file. Default: ' + Policy.POLICY_CFG,
                               metavar='FILE', default=Policy.POLICY_CFG)

        MarketplaceUtil.addEndpointOption(self.parser)

        self.options, self.args = self.parser.parse_args()

        self.checkArgumentsLength()

    def checkArgumentsLength(self):
        if len(self.args) < 1:
            self.usageExitTooFewArguments()
        if len(self.args) > 2:
            self.usageExitTooManyArguments()

    def doWork(self):
        configHolder = ConfigHolder(self.options.__dict__)

        imageId = self.args[0]

        policy = Policy(configHolder)
        filtered = policy.check(imageId)
        first = filtered[0]
        rootUrl = policy.marketplaceEndpoint + '/metadata'
        res = '%s/%s/%s/%s' % (rootUrl, first.identifier, first.endorser, first.created)
        print res


if __name__ == '__main__':
    try:
        MainProgram()
    except KeyboardInterrupt:
        print '\n\nExecution interrupted by the user... goodbye!'
