#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012, Centre National de la Recherche Scientifique (CNRS)
#
# 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.commandbase.CommandBase import CommandBase
from stratuslab.cloudinit import Util

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

LogUtil.get_console_logger()


class MainProgram(CommandBase):
    """
    A command-line utility for generating a cloud-init context file.
    The output file is always named cloud-init.txt and written to the
    current directory.
    """
    def __init__(self):
        self.image = None
        super(MainProgram, self).__init__()

    def parse(self):
        self.parser.usage = '%prog file-desc ...'

        self.parser.description = '''
Creates a context file for use with the CloudInit virtual machine
contextualization.  Each argument is a mime-type and file name pair,
separated by a comma.  The pseudo-mime-type 'ssh' is used for ssh
keys.  The output is in the file 'cloud-init.txt'.
'''

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

    def checkOptions(self):
        pass

    def doWork(self):
        contents = Util.context_file(self.args)

        with open('cloud-init.txt', 'wb') as f:
            f.write(contents)
            f.write("\n")


def main():
    try:
        MainProgram()
    except KeyboardInterrupt:
        print '\n\nExecution interrupted by the user... goodbye!'
    return 0
