b.liu | e958203 | 2025-04-17 19:18:16 +0800 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | |
| 3 | from os import getenv |
| 4 | from pathlib import Path |
| 5 | from sys import argv |
| 6 | import hashlib |
| 7 | import json |
| 8 | |
| 9 | if len(argv) != 2: |
| 10 | print("ERROR: JSON info script requires output arg") |
| 11 | exit(1) |
| 12 | |
| 13 | json_path = Path(argv[1]) |
| 14 | file_path = Path(getenv("FILE_DIR")) / getenv("FILE_NAME") |
| 15 | |
| 16 | if not file_path.is_file(): |
| 17 | print("Skip JSON creation for non existing file", file_path) |
| 18 | exit(0) |
| 19 | |
| 20 | |
| 21 | def get_titles(): |
| 22 | titles = [] |
| 23 | for prefix in ["", "ALT0_", "ALT1_", "ALT2_", "ALT3_", "ALT4_", "ALT5_"]: |
| 24 | title = {} |
| 25 | for var in ["vendor", "model", "variant"]: |
| 26 | if getenv("DEVICE_{}{}".format(prefix, var.upper())): |
| 27 | title[var] = getenv("DEVICE_{}{}".format(prefix, var.upper())) |
| 28 | |
| 29 | if title: |
| 30 | titles.append(title) |
| 31 | |
| 32 | if not titles: |
| 33 | titles.append({"title": getenv("DEVICE_TITLE")}) |
| 34 | |
| 35 | return titles |
| 36 | |
| 37 | |
| 38 | device_id = getenv("DEVICE_ID") |
| 39 | |
| 40 | sha256_hash = hashlib.sha256() |
| 41 | with open(str(file_path),"rb") as f: |
| 42 | # Read and update hash string value in blocks of 4K |
| 43 | for byte_block in iter(lambda: f.read(4096),b""): |
| 44 | sha256_hash.update(byte_block) |
| 45 | |
| 46 | hash_file = sha256_hash.hexdigest() |
| 47 | |
| 48 | if file_path.with_suffix(file_path.suffix + ".sha256sum").exists(): |
| 49 | hash_unsigned = ( |
| 50 | file_path.with_suffix(file_path.suffix + ".sha256sum").read_text().strip() |
| 51 | ) |
| 52 | else: |
| 53 | hash_unsigned = hash_file |
| 54 | |
| 55 | file_info = { |
| 56 | "metadata_version": 1, |
| 57 | "target": "{}/{}".format(getenv("TARGET"), getenv("SUBTARGET")), |
| 58 | "version_code": getenv("VERSION_CODE"), |
| 59 | "version_number": getenv("VERSION_NUMBER"), |
| 60 | "source_date_epoch": int(getenv("SOURCE_DATE_EPOCH")), |
| 61 | "profiles": { |
| 62 | device_id: { |
| 63 | "image_prefix": getenv("DEVICE_IMG_PREFIX"), |
| 64 | "images": [ |
| 65 | { |
| 66 | "type": getenv("FILE_TYPE"), |
| 67 | "name": getenv("FILE_NAME"), |
| 68 | "sha256": hash_file, |
| 69 | "sha256_unsigned": hash_unsigned, |
| 70 | } |
| 71 | ], |
| 72 | "device_packages": getenv("DEVICE_PACKAGES").split(), |
| 73 | "supported_devices": getenv("SUPPORTED_DEVICES").split(), |
| 74 | "titles": get_titles(), |
| 75 | } |
| 76 | }, |
| 77 | } |
| 78 | |
| 79 | if getenv("FILE_FILESYSTEM"): |
| 80 | file_info["profiles"][device_id]["images"][0]["filesystem"] = getenv( |
| 81 | "FILE_FILESYSTEM" |
| 82 | ) |
| 83 | |
| 84 | json_path.write_text(json.dumps(file_info, separators=(",", ":"))) |