44b4031f85e8d8e843b7f0abe802b4a7244c7bba
[openwrt/openwrt.git] / scripts / json_add_image_info.py
1 #!/usr/bin/env python3
2
3 import json
4 import os
5 import hashlib
6
7
8 def e(variable, default=None):
9 return os.environ.get(variable, default)
10
11
12 json_path = "{}{}{}.json".format(e("BIN_DIR"), os.sep, e("IMAGE_PREFIX"))
13
14 with open(os.path.join(e("BIN_DIR"), e("IMAGE_NAME")), "rb") as image_file:
15 image_hash = hashlib.sha256(image_file.read()).hexdigest()
16
17
18 def get_titles():
19 titles = []
20 for prefix in ["", "ALT0_", "ALT1_", "ALT2_"]:
21 title = {}
22 for var in ["vendor", "model", "variant"]:
23 if e("DEVICE_{}{}".format(prefix, var.upper())):
24 title[var] = e("DEVICE_{}{}".format(prefix, var.upper()))
25
26 if title:
27 titles.append(title)
28
29 if not titles:
30 titles.append({"title": e("DEVICE_TITLE")})
31
32 return titles
33
34
35 if not os.path.exists(json_path):
36 device_info = {
37 "id": e("DEVICE_ID"),
38 "image_prefix": e("IMAGE_PREFIX"),
39 "images": [],
40 "metadata_version": 1,
41 "supported_devices": e("SUPPORTED_DEVICES").split(),
42 "target": "{}/{}".format(e("TARGET"), e("SUBTARGET", "generic")),
43 "titles": get_titles(),
44 "version_commit": e("VERSION_CODE"),
45 "version_number": e("VERSION_NUMBER"),
46 }
47 else:
48 with open(json_path, "r") as json_file:
49 device_info = json.load(json_file)
50
51 image_info = {"type": e("IMAGE_TYPE"), "name": e("IMAGE_NAME"), "sha256": image_hash}
52 device_info["images"].append(image_info)
53
54 with open(json_path, "w") as json_file:
55 json.dump(device_info, json_file, sort_keys=True, indent=" ")