18af98dbdb20c022524f60dc70d8830edd4bfc6e
[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 os
6 import yaml
7 from jinja2 import Environment, FileSystemLoader
8
9 PARSER = argparse.ArgumentParser()
10 PARSER.add_argument("--yaml", "-y", type=str, required=True)
11 PARSER.add_argument("--jinja2", "-j", type=str, required=True)
12 ARGS = PARSER.parse_args()
13
14 # Processor architecture vs DPKG architecture mapping
15 DPKG_ARCH_TABLE = {
16     'aarch64': 'arm64',
17     'x86_64': 'amd64',
18 }
19 ARCH_DPKG_TABLE = dict(zip(DPKG_ARCH_TABLE.values(), DPKG_ARCH_TABLE.keys()))
20
21 # Custom filter to allow simple IP address operations returning
22 # a new address from an upper or lower (negative) index
23 def ipaddr_index(base_address, index):
24     """Return IP address in given network at given index"""
25     try:
26         base_address_str = unicode(base_address)
27     #pylint: disable=unused-variable
28     except NameError as ex:
29         base_address_str = str(base_address)
30     return ipaddress.ip_address(base_address_str) + int(index)
31
32 # Custom filter to convert between processor architecture
33 # (as reported by $(uname -m)) and DPKG-style architecture
34 def dpkg_arch(arch, to_dpkg=True):
35     """Return DPKG-compatible from processor arch and vice-versa"""
36     if to_dpkg:
37         return DPKG_ARCH_TABLE[arch]
38     else:
39         return ARCH_DPKG_TABLE[arch]
40
41 ENV = Environment(loader=FileSystemLoader('./'))
42 ENV.filters['ipaddr_index'] = ipaddr_index
43 ENV.filters['dpkg_arch'] = dpkg_arch
44
45 with open(ARGS.yaml) as _:
46     DICT = yaml.safe_load(_)
47
48 # If an installer descriptor file (IDF) exists, include it (temporary)
49 IDF_PATH = '/idf-'.join(os.path.split(ARGS.yaml))
50 if os.path.exists(IDF_PATH):
51     with open(IDF_PATH) as _:
52         IDF = yaml.safe_load(_)
53         DICT['idf'] = IDF['idf']
54
55 # Print dictionary generated from yaml (uncomment for debug)
56 # print(DICT)
57
58 # Render template and print generated conf to console
59 TEMPLATE = ENV.get_template(ARGS.jinja2)
60 #pylint: disable=superfluous-parens
61 print(TEMPLATE.render(conf=DICT))