#!/usr/bin/env python3

import os
import sys

from impl.plugininstall.plugininstall import Deploy


usage = """
usage: gs_install_plugin
        -h, --help                Get help information
        -p                        Specify plugin package file path 
                                  (Default: $GPHOME/script/static/Plugins-*.tar.gz)
        -X                        Specify the XML file path
        --all                     Install all plugins (Default)
        --force                   Specify override old plugin
        --plugins                 Specify batch plugins name
        --PLUGIN_NAME             Specify fixed plugin name
        --debug                   Print debug log
        """

if __name__ == '__main__':
    plugins = []
    xml = ""
    pkg = ""
    plugins_flag = False
    pkg_flag = False
    xml_flag = False
    force_flag = False
    debug = False
    for idx, arg in enumerate(sys.argv):
        if idx == 0:
            continue
        if plugins_flag:
            if arg.startswith('--'):
                plugins_flag = False
            else:
                plugins.append(arg)
            continue
        if pkg_flag:
            pkg = arg
            if not os.path.exists(pkg):
                print("Not found package: %s" % pkg)
                exit(1)
            pkg_flag = False
            continue
        if xml_flag:
            xml = arg
            if not os.path.exists(xml):
                print("Not found xml file: %s" % xml)
                exit(1)
            xml_flag = False
            continue

        if arg == "-h" or arg == "--help":
            print(usage)
            exit(0)
        elif arg == "-p":
            if len(sys.argv) < idx+2:
                print("Please add the plugin package path with parameter '-p'")
                exit(1)
            pkg_flag = True
        elif arg == "-X":
            if len(sys.argv) < idx+2:
                print("Please add the xml file path with parameter '-X'")
                exit(1)
            xml_flag = True
        elif arg == "--all":
            plugins.append("all")
        elif arg == "--plugins":
            plugins_flag = True
        elif arg == "--force":
            force_flag = True
        elif arg == "--debug":
            debug = True
        elif arg.startswith('--'):
            arg = arg.replace("--", "")
            plugins.append(arg)
        else:
            print("Invalid parameter: %s" % arg)
            exit(1)
    if len(plugins) == 0:
        plugins.append("all")
    deploy = Deploy(xml, pkg, force_flag, debug)
    deploy.plugin_deploy(plugins)
