summaryrefslogtreecommitdiffstats
path: root/ogcli
blob: 27388855486c396f160e6f26eaef6961ccfa1d94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python3

# Copyright (C) 2020-2021 Soleta Networks <info@soleta.eu>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.

from inspect import ismethod, getmembers

from cli.cli import OgCLI
import signal
import argparse
import json
import sys

OG_CLI_CFG_PATH = "/opt/opengnsys/etc/ogcli.json"

def sigint_handler(signum, frame):
	print("User has pressed ctrl-C, interrupting...")
	sys.exit(1)

class CLI():
    def __init__(self):
        signal.signal(signal.SIGPIPE, signal.SIG_IGN)
        signal.signal(signal.SIGINT, sigint_handler)
        try:
            with open(OG_CLI_CFG_PATH, 'r') as json_file:
                self.cfg = json.load(json_file)
        except json.JSONDecodeError:
            sys.exit(f'ERROR: Failed parse malformed JSON file '
                     f'{OG_CLI_CFG_PATH}')
        except:
            sys.exit(f'ERROR: cannot open {OG_CLI_CFG_PATH}')

        required_cfg_params = {'api_token', 'ip', 'port'}
        difference_cfg_params = required_cfg_params - self.cfg.keys()
        if len(difference_cfg_params) > 0:
            sys.exit(f'Missing {difference_cfg_params} key in '
                     f'json config file')

        self.ogcli = OgCLI(self.cfg)

        parser = argparse.ArgumentParser(prog='ogcli')
        parser.add_argument('command', help='Subcommand to run', nargs='?',
                            choices=[attr for attr, _ in getmembers(self.ogcli, lambda x: ismethod(x))
                                     if not attr.startswith('_')])
        args = parser.parse_args(sys.argv[1:2])

        if args.command is None:
            print('Missing subcommand', file=sys.stderr)
            parser.print_help(file=sys.stderr)
            sys.exit(1)

        if not hasattr(self.ogcli, args.command):
            print('Invalid subcommand', file=sys.stderr)
            parser.print_help(file=sys.stderr)
            sys.exit(1)

        # Call the command with the same name.
        getattr(self.ogcli, args.command)(sys.argv[2:])


if __name__ == "__main__":
    CLI()