#!/usr/bin/python

# the standalone tool to create, deploy and launch kvm images to
# run mic for image creation

import os, sys, io
import optparse
import ConfigParser

from kvmic import *
from kvmic.__version__ import VERSION

VERBOSE = False

CMDS = ('create', 'deploy', 'run')

DEFAULTCONF = """[general]
resdir = /usr/share/kvmic
imgdir = /var/tmp/mic2image

[run]
usekvm = no
usescreen = no
tmpimgdir = /var/tmp/mic2image.tmp

[deploy]
;

; The following section is for mic configuration
[common]
; mic general settings
distro_name = Tizen
plugin_dir = /usr/lib/mic/plugins

[create]
; mic create default options
base_buildid = invalid_id
tmpdir= /var/tmp/mic
cachedir= /var/tmp/mic/cache
outdir= ./mic-output
runtime= bootstrap

pkgmgr = auto

# to skip all ssl verification for repos
#ssl_verify = no

[bootstrap]
rootdir=/var/tmp/mic-bootstrap
packages=mic-bootstrap-x86-arm

"""

CONFS = {}

def do_deploy():
    pass

def main():
    usage = 'Usage: %prog [options]'

    optparser = optparse.OptionParser(usage, version=VERSION)

    optparser.add_option('-m', '--command', default='run',
                         help='sub-command among: create, deploy, run')
    optparser.add_option('-v', '--verbose', default=None,
                         help='show verbose help message')
    optparser.add_option('', '--get-defconf', dest="get_defconf", action="store_true",
                         help='print default config')
    optparser.add_option('-c', '--config', default=None,
                         help='path of configuration file')
    optparser.add_option('-b', '--buildid', default=None,
                         help='buildid of creating image')
    optparser.add_option('-k', '--ks', default=None,
                         help='path of kickstart of creating image')
    optparser.add_option('-d', '--destdir', default=None,
                         help='dir to store output image files')
    optparser.add_option('-T', '--timeout', default='60m',
                         help='time of timeout control for kvm instance, in [number]{s|m|h} format, 0 for infinite')

    opts, args = optparser.parse_args()

    if opts.command not in CMDS:
        msger.error('invalid command %s' % opts.command)

    command = opts.command

    if opts.verbose:
        global VERBOSE
        VERBOSE = True

    if opts.config:
        confp = os.path.abspath(os.path.expanduser(opts.config))
    else:
        confp = os.path.expanduser('~/.kvmic.conf')
        if not os.path.isfile(confp):
            confp = '/etc/kvmic.conf'

    if opts.get_defconf:
        msger.info('Default content of ~/.kvmic.conf as blow:')
        print DEFAULTCONF
        return 0

    try:
        with open(confp) as f:
            str_conf = f.read()
    except:
        msger.warning('cannot read config file: %s, use default settings' % confp)
        str_conf = DEFAULTCONF

    config = ConfigParser.ConfigParser()
    config.readfp(io.BytesIO(str_conf))

    global CONFS
    try:
        CONFS['resdir'] = config.get('general', 'resdir')
        CONFS['imgdir'] = config.get('general', 'imgdir')

        if command == 'create':
            CONFS['base_buildid'] = config.get(command, 'base_buildid')

        if command == 'run':
            CONFS['usekvm'] = config.get(command, 'usekvm')
            CONFS['usescreen'] = config.get(command, 'usescreen')
            CONFS['tmpimgdir'] = config.get(command, 'tmpimgdir')

    except ConfigParser.NoOptionError, e:
        msger.error('In config, %s' % str(e))

    if command == 'run':
        try:
            # MIC use the settings in the same configuraiton file with kvmic
            CONFS['mic_conf'] = os.path.abspath(confp)
        except ConfigParser.NoOptionError, e:
            CONFS['mic_conf'] = None

    if command == 'create':
        creater.do(CONFS)

    elif command == 'run':
        if not opts.buildid:
            msger.error('Must specify buildid using -b|--buildid')

        if not opts.ks:
            msger.error('Must specify path of kickstart file using -k|--ks')

        if not opts.destdir:
            msger.error('Must specify dir for dest image files using -d|--destdir')

        tos = opts.timeout[:-1]
        unit = opts.timeout[-1:].lower()
        try:
            if unit not in ('h', 's', 'm'):
                raise Exception()
            tos = int(tos)
            if unit == 'h':
                tos = tos * 3600
            elif unit == 'm':
                tos = tos * 60
        except:
            msger.error('Timeout value should be in [number]{s|m|h} format with valid numbers')

        return launcher.do(CONFS, opts.buildid, opts.ks, opts.destdir, tos)

    elif command == 'deploy':
        deployer.do()

    return 0

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