#!/usr/bin/python3
#
# ec2-converter: Convert a virtual appliance image in an EC2 AMI
#
# Copyright 2008, Red Hat  Inc.
# Joseph Boggs <jboggs@redhat.com>
# Copyright 2018, Neal Gompa <ngompa13@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

from __future__ import print_function
import os
import sys
import optparse
import logging
import imgcreate
import ec2convert.ec2config as ec2config
import time
    
class Usage(Exception):
    def __init__(self, msg = None, no_error = False):
        Exception.__init__(self, msg, no_error)
        
        
def parse_options(args):
    parser = optparse.OptionParser()
    
    parser.add_option("-f", "--imagefile", type="string", dest="imagefile",
                      help="Image filename or directory")
 
    parser.add_option("-n", "--imagename", type="string", dest="imagename",
                      help="Image name")
         
    parser.add_option("-t", "--tmpdir", type="string",
                      dest="tmpdir", default="/var/tmp",
                      help="Temporary directory to use (default: /var/tmp)")
            
    parser.add_option("--inputtype",type="string",
                      dest="inputtype", default=None,
                      help="Input image type(loopbackfs, diskimage, directory")
            
    parser.add_option("--ssh",type="string",
                      dest="ssh", default="yes",
                      help="Configure ssh to allow remote logins, default is yes,set to no if ssh is not installed")

    parser.add_option("--rpmcheck",type="string",
                      dest="rpmcheck", default="yes",
                      help="Perform rpm package checks, default is yes, set to no to override")

    imgcreate.setup_logging(parser)

    (options, args) = parser.parse_args()

    return options

    
def main():
    try:
        options = parse_options(sys.argv[1:])
    except Usage as opterr:
        (msg, no_error) = opterr.args
        if no_error:
            out = sys.stdout
            ret = 0
        else:
            out = sys.stderr
            ret = 2
        if msg:
            print(msg, file=out)
        return ret
    
    if os.geteuid () != 0:
        logging.error("You must run as root")
        return 1
    
    if not options.imagefile:
        logging.error("Imagefile required to convert")
        return 1
    
    if not options.inputtype:
        logging.error("--inputtype must be defined")
        return 1        
        
    if options.imagename:
        imagename = options.imagename
    else:
        suffix = time.strftime("%Y%m%d%H%M") + ".img"
        imagename = "ec2-" + suffix    
        
    rpmcheck = options.rpmcheck == "yes"
    sshconfig = options.ssh == "yes"
    
    success = ec2config.convert(options.imagefile, options.inputtype, \
                    options.tmpdir, rpmcheck, sshconfig, imagename)
    
    if success:            
        print("\n\nEC2 Image created as %s" % imagename, file=sys.stdout)
        print("\n\nYou now need to bundle and upload the image to EC2 using the EC2 tools", file=sys.stdout)
        print("Available at:  http://s3.amazonaws.com/ec2-downloads/ec2-ami-tools.noarch.rpm\n", file=sys.stdout)
        return 0
    else:
        print("\nConversion failed", file=sys.stdout)
        return 1

if __name__ == "__main__":
    sys.exit(main())
