#!/usr/bin/env python

import platform
import sys
import os
import re
import importlib

plugin_folder = os.path.join(os.path.dirname(__file__), 'includes')

os_distro = str(platform.linux_distribution()[0]).split(' ')[0]
os_version = str(platform.linux_distribution()[1]).split('.')[0]

if os_distro != 'CentOS' or os_version < 7:
   print "OS: {distro} {version}".format(distro=os_distro,version=os_version)
   print "Operating system distro should be Centos 7 or higher!"
   exit(7)

# make sure we are root
if os.geteuid() != 0:
    print "You must run this utility as root!"
    sys.exit(0)

try:
   import pip
except ImportError:
   print "[ >NO MODULE 'PIP' FOUND< ]"
   print "Installing module pip ..."
   os.system('yum -y install epel-release')
   os.system('yum-config-manager --disable epel')
   os.system('yum -y --enablerepo=epel install python-pip')
   os.system('pip install --upgrade pip')

try:
   import click
except ImportError:
   print "[ >NO MODULE '{pk}' FOUND< ]".format(pk='click')
   print "[ Installing module '{pk}' ... ]".format(pk='click')
   import pip
   cmd = "pip install {pk} --upgrade".format(pk='click')
   os.system(cmd)
   import click

if len(sys.argv) <= 1:
   print "Ask for help with 'cloudctl help' command."
   exit(11)
  
if str(sys.argv[1])+".py" not in os.listdir(plugin_folder):
   print sys.argv[1] + \
    """ is not defined. Use one of below ones..
Providers:
    server
    client
    help  """
   exit(13)


class MyCLI(click.MultiCommand):

    def list_commands(self, ctx):
        rv = []
        for filename in os.listdir(plugin_folder):
            if filename.endswith('.py'):
                rv.append(filename[:-3])
        rv.sort()
        return rv

    def get_command(self, ctx, name):
        ns = {}
        fn = os.path.join(plugin_folder, name + '.py')
        with open(fn) as f:
            code = compile(f.read(), fn, 'exec')
            eval(code, ns, ns)
        return ns['cli']

cli = MyCLI(help='This tool\'s subcommands are loaded from a '
            'plugin folder dynamically.')

if __name__ == '__main__':
    cli()


