#!/usr/bin/python
"""
Copyright (C) 2011 Konstantin Andrusenko
    See the documentation for further information on copyrights,
    or contact the author. All Rights Reserved.

@author Konstantin Andrusenko
@date November 30, 2011

plugin-installer is utility for installation plugins for NodesManager and NodeAgent
"""

import yaml
import os
import sys
import shutil
from datetime import datetime
import blik

BASE_PATH = os.path.dirname(os.path.abspath(blik.__file__))
CONSOLE_MENU_DIR = os.path.join(BASE_PATH, 'console/menu')
CONSOLE_PLUGINS_DIR = os.path.join(BASE_PATH, 'console/plugins')
NM_PLUGINS_DIR = os.path.join(BASE_PATH, 'nodesManager/plugins')
NA_PLUGINS_DIR = os.path.join(BASE_PATH, 'nodeAgent/plugins')

def print_log(message):
    print ('[%s] %s' % (datetime.now(), message))

def install_console(plugins_dir):
    menu_dir = os.path.join(plugins_dir, 'menu')
    if not os.path.exists(menu_dir):
        raise Exception('Menu directory is not found in %s!'%plugins_dir)

    apps_dir = os.path.join(plugins_dir, 'applications')
    if not os.path.exists(apps_dir):
        raise Exception('Applications directory is not found in %s!'%plugins_dir)

    files = os.listdir(menu_dir)
    for f_name in files:
        if f_name.endswith('.json'):
            shutil.copy(os.path.join(menu_dir, f_name), CONSOLE_MENU_DIR)

    subdirs = os.listdir(apps_dir)
    for sdir_name in subdirs:
        sdir = os.path.join(apps_dir,sdir_name)
        if not os.path.isdir(sdir):
            continue

        dest = os.path.join(CONSOLE_PLUGINS_DIR, sdir_name)
        if os.path.exists(dest):
            shutil.rmtree(dest)

        shutil.copytree(sdir, dest)

def install_operations_plugins(plugins_dir, dest_dir):
    files = os.listdir(plugins_dir)
    for file_name in files:
        path = os.path.join(plugins_dir, file_name)
        dest = os.path.join(dest_dir, file_name)

        if os.path.isdir(path):
            if os.path.exists(dest):
                shutil.rmtree(dest)
            shutil.copytree(path, dest)
        else:
            shutil.copy(path, dest)

#-----------------------------------------------------------------------------------


def main(plugins_dir, is_console, is_management=True):
    try:
        if is_console:
            install_console(plugins_dir)
        else:
            if is_management:
                install_operations_plugins(plugins_dir, NM_PLUGINS_DIR)
            else:
                install_operations_plugins(plugins_dir, NA_PLUGINS_DIR)

        print_log('Operations installed successful!')
    except Exception, err:
        print_log(err)
        print_log('Operations installation failed!')
        return 1

    return 0

#-----------------------------------------------------------------------------------

def usage():
    print 'Usage: plugin-installer --console|--operations  [--management|--agent] <plugins dir>'
    sys.exit(1)

if __name__ == '__main__':
    if len(sys.argv) < 3:
        usage()

    plugins_dir = sys.argv[-1]
    plugin_type = sys.argv[1]
    plugin_dest = '--management'
    if len(sys.argv)==4:
        plugin_dest = sys.argv[2]

    if plugin_type == '--console':
        is_console = True
    elif plugin_type == '--operations':
        is_console = False
    else:
        usage()

    if plugin_dest == '--management':
        is_management = True
    elif plugin_dest  == '--agent':
        is_management = False
    else:
        usage()

    ret = main(plugins_dir, is_console, is_management)
    sys.exit(ret)

