#!/usr/bin/python
"""
Machine pool wizard

Copyright 2014 Red Hat, Inc.
Licensed under the GNU General Public License, version 2 as
published by the Free Software Foundation; see COPYING for details.
"""

__author__ = """
jprochaz@redhat.com (Jiri Prochazka)
"""
from lnst.Controller.Wizard import Wizard
import sys
import getopt

RETVAL_PASS = 0
RETVAL_ERR = 1


def help(retval=0):
    print "Usage:\n"\
          " lnst-pool-wizard [mode] [hostname[:port]]\n"\
          "\n"\
          "Modes:\n"\
          " -h, --help                 display this help text and exit\n"\
          " -p, --pool_dir <directory> set the pool dir (works both in) "\
          "interactive and noninteractive mode\n"\
          " -i, --interactive          start wizard in interactive mode (default)"\
          " -n, --noninteractive       start wizard in noninteractive mode\n"\
          " -v, --virtual              start wizard in mode for VMs\n"\
          "Examples:\n"\
          " lnst-pool-wizard --interactive\n"\
          " lnst-pool-wizard hostname1:1234 hostname2\n"\
          " lnst-pool-wizard --noninteractive 192.168.122.2\n"\
          " lnst-pool-wizard -n 192.168.122.2:8888 192.168.122.4\n"\
          " lnst-pool-wizard -p \".pool/\" -n 192.168.1.1:8877 192.168.122.4"
    sys.exit(retval)


def main():
    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            "hinvp:",
            ["help", "interactive", "noninteractive", "virtual", "pool_dir="]
        )
    except getopt.GetoptError as err:
        sys.stderr.write(str(err))
        help(RETVAL_ERR)

    pool_dir = None
    mode = "interactive"
    hostlist = None

    for opt, arg  in opts:
        if opt in ("-h", "--help"):
            help()
        elif opt in ("-i", "--interactive"):
            mode = "interactive"
        elif opt in ("-n", "--noninteractive"):
            if not args:
                sys.stderr.write("No hostnames entered\n")
                return RETVAL_ERR
            mode = "noninteractive"
        elif opt in ("-v", "--virtual"):
            mode = "virtual"
        elif opt in ("-p", "--pool_dir"):
            if not arg:
                sys.stderr.write("No pool directory specified\n")
            else:
                pool_dir = arg
        else:
            help(RETVAL_ERR)

    if len(args) > 0:
        hostlist = args

    wizard = Wizard()

    if mode == "noninteractive":
        wizard.noninteractive(hostlist, pool_dir)
    elif mode == "virtual":
        wizard.virtual(pool_dir)
    else:
        wizard.interactive(hostlist, pool_dir)

    sys.exit(RETVAL_PASS)


if __name__ == "__main__":
    main()
