# Copyright 2009-2014 Justin Riley
#
# This file is part of TethysCluster.
#
# TethysCluster is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# TethysCluster is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with TethysCluster. If not, see <http://www.gnu.org/licenses/>.

from tethyscluster.logger import log

from base import CmdBase


class CmdCreateKey(CmdBase):
    """
    createkey [options] <name>

    Create a new Amazon EC2 keypair
    """
    names = ['createkey', 'ck']

    def addopts(self, parser):
        parser.add_option("-o", "--output-file", dest="output_file",
                          action="store", type="string", default=None,
                          help="Save the new keypair to a file")
        parser.add_option("-i", "--import-key", dest="rsa_key_file",
                          action="callback", type="string", default=None,
                          callback=self._file_exists,
                          help="Import an existing RSA key to EC2")
        # parser.add_option("-a","--add-to-config", dest="add_to_config",
        #                   action="store_true", default=False, help="add new
        #                   keypair to TethysCluster config")

    def execute(self, args):
        if len(args) != 1:
            self.parser.error("please provide a key name")
        name = args[0]
        ofile = self.opts.output_file
        rsa_file = self.opts.rsa_key_file
        if rsa_file:
            kp = self.ec2.import_keypair(name, rsa_file)
        else:
            kp = self.ec2.create_keypair(name, output_file=ofile)
        log.info("Successfully created keypair: %s" % name)
        log.info("fingerprint: %s" % kp.fingerprint)
        if ofile and not rsa_file:
            log.info("keypair written to %s" % ofile)
        elif kp.material:
            log.info("contents: \n%s" % kp.material)
