#!/usr/bin/env python3


import os
import sys

from impl.plugininstall.plugininstall import Deploy


usage = """
usage: gs_install_plugin_local
        -h, --help                Get help information
        -p                        Specify plugin package file path
                                  (Default: $GPHOME/script/static/Plugins-*.tar.gz)
        --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 = []
    pkg = ""
    plugins_flag = False
    pkg_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 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 == "--all":
            plugins.append("all")
        elif arg == "--force":
            force_flag = True
        elif arg == "--plugins":
            plugins_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(plugin_pkg=pkg,force=force_flag, debug=debug)
    deploy.plugin_deploy(plugins)
