1 | #!/usr/bin/env python3 |
---|
2 | |
---|
3 | # Copyright (C) 2020-2021 Soleta Networks <info@soleta.eu> |
---|
4 | # |
---|
5 | # This program is free software: you can redistribute it and/or modify it under |
---|
6 | # the terms of the GNU Affero General Public License as published by the |
---|
7 | # Free Software Foundation; either version 3 of the License, or |
---|
8 | # (at your option) any later version. |
---|
9 | |
---|
10 | from inspect import ismethod, getmembers |
---|
11 | |
---|
12 | from cli.cli import OgCLI |
---|
13 | import argparse |
---|
14 | import json |
---|
15 | import sys |
---|
16 | |
---|
17 | OG_CLI_CFG_PATH = "/opt/opengnsys/etc/ogcli.json" |
---|
18 | |
---|
19 | |
---|
20 | class CLI(): |
---|
21 | def __init__(self): |
---|
22 | try: |
---|
23 | with open(OG_CLI_CFG_PATH, 'r') as json_file: |
---|
24 | self.cfg = json.load(json_file) |
---|
25 | except json.JSONDecodeError: |
---|
26 | sys.exit(f'ERROR: Failed parse malformed JSON file ' |
---|
27 | f'{OG_CLI_CFG_PATH}') |
---|
28 | except: |
---|
29 | sys.exit(f'ERROR: cannot open {OG_CLI_CFG_PATH}') |
---|
30 | |
---|
31 | required_cfg_params = {'api_token', 'ip', 'port'} |
---|
32 | difference_cfg_params = required_cfg_params - self.cfg.keys() |
---|
33 | if len(difference_cfg_params) > 0: |
---|
34 | sys.exit(f'Missing {difference_cfg_params} key in ' |
---|
35 | f'json config file') |
---|
36 | |
---|
37 | self.ogcli = OgCLI(self.cfg) |
---|
38 | |
---|
39 | parser = argparse.ArgumentParser(prog='ogcli') |
---|
40 | parser.add_argument('command', help='Subcommand to run', nargs='?', |
---|
41 | choices=[attr for attr, _ in getmembers(self.ogcli, lambda x: ismethod(x)) |
---|
42 | if not attr.startswith('_')]) |
---|
43 | args = parser.parse_args(sys.argv[1:2]) |
---|
44 | |
---|
45 | if not hasattr(self.ogcli, args.command): |
---|
46 | parser.print_help() |
---|
47 | sys.exit('Unknown command') |
---|
48 | |
---|
49 | # Call the command with the same name. |
---|
50 | getattr(self.ogcli, args.command)(sys.argv[2:]) |
---|
51 | |
---|
52 | |
---|
53 | if __name__ == "__main__": |
---|
54 | CLI() |
---|