a32367af7608b3492010a7f5b1c80536bc1930c3
[pharos.git] / config / utils / generate_config.py
1 #!/usr/bin/python
2 """This module does blah blah."""
3 import argparse
4 import ipaddress
5 import yaml
6 from jinja2 import Environment, FileSystemLoader
7
8 PARSER = argparse.ArgumentParser()
9 PARSER.add_argument("--yaml", "-y", type=str, required=True)
10 PARSER.add_argument("--jinja2", "-j", type=str, required=True)
11 ARGS = PARSER.parse_args()
12
13 # Processor architecture vs DPKG architecture mapping
14 DPKG_ARCH_TABLE = {
15     'aarch64': 'arm64',
16     'x86_64': 'amd64',
17 }
18 ARCH_DPKG_TABLE = dict(zip(DPKG_ARCH_TABLE.values(), DPKG_ARCH_TABLE.keys()))
19
20 # Custom filter to allow simple IP address operations returning
21 # a new address from an upper or lower (negative) index
22 def ipaddr_index(base_address, index):
23     """Return IP address in given network at given index"""
24     try:
25         base_address_str = unicode(base_address)
26     #pylint: disable=unused-variable
27     except NameError as ex:
28         base_address_str = str(base_address)
29     return ipaddress.ip_address(base_address_str) + int(index)
30
31 # Custom filter to convert between processor architecture
32 # (as reported by $(uname -m)) and DPKG-style architecture
33 def dpkg_arch(arch, to_dpkg=True):
34     """Return DPKG-compatible from processor arch and vice-versa"""
35     if to_dpkg:
36         return DPKG_ARCH_TABLE[arch]
37     else:
38         return ARCH_DPKG_TABLE[arch]
39
40 ENV = Environment(loader=FileSystemLoader('./'))
41 ENV.filters['ipaddr_index'] = ipaddr_index
42 ENV.filters['dpkg_arch'] = dpkg_arch
43
44 with open(ARGS.yaml) as _:
45     DICT = yaml.safe_load(_)
46
47 # Print dictionary generated from yaml (uncomment for debug)
48 # print(DICT)
49
50 # Render template and print generated conf to console
51 TEMPLATE = ENV.get_template(ARGS.jinja2)
52 #pylint: disable=superfluous-parens
53 print(TEMPLATE.render(conf=DICT))