1"""Extract information about vbmeta (digest/size) required in (androidboot.*)
2bootconfig. It uses avbtool to find some values such as vbmeta size, digest"""
3#!/usr/bin/env python3
4
5import sys
6import subprocess
7
8def main(args):
9    """Runs avbtool to generate vbmeta related bootconfigs"""
10    avbtool = args[0]
11    vbmeta_img = args[1]
12    hash_algorithm = 'sha256'
13    size = 0
14
15    with subprocess.Popen([avbtool, 'version'],
16                            stdout=subprocess.PIPE,
17                            stderr=subprocess.STDOUT) as proc:
18        stdout, _ = proc.communicate()
19        avb_version = stdout.decode("utf-8").split(" ")[1].strip()
20        avb_version = avb_version[0:avb_version.rfind('.')]
21
22    with subprocess.Popen([avbtool, 'info_image', '--image', vbmeta_img],
23                           stdout=subprocess.PIPE,
24                           stderr=subprocess.STDOUT) as proc:
25        stdout, _ = proc.communicate()
26        for line in stdout.decode("utf-8").split("\n"):
27            line = line.split(":")
28            if line[0] in \
29                ['Header Block', 'Authentication Block', 'Auxiliary Block']:
30                size += int(line[1].strip()[0:-6])
31
32    with subprocess.Popen([avbtool, 'calculate_vbmeta_digest',
33                            '--image', vbmeta_img,
34                            '--hash_algorithm', hash_algorithm],
35                           stdout=subprocess.PIPE,
36                           stderr=subprocess.STDOUT) as proc:
37        stdout, _ = proc.communicate()
38        vbmeta_hash = stdout.decode("utf-8").strip()
39
40    print(f'androidboot.vbmeta.size = {size}')
41    print(f'androidboot.vbmeta.digest = \"{vbmeta_hash}\"')
42    print(f'androidboot.vbmeta.hash_alg = \"{hash_algorithm}\"')
43    print(f'androidboot.vbmeta.avb_version = \"{avb_version}\"')
44    print('androidboot.veritymode = "enforcing"')
45    print('androidboot.vbmeta.invalidate_on_error = "yes"')
46    print('androidboot.vbmeta.device_state = "locked"')
47    print('androidboot.vbmeta.device = "/dev/block/by-name/vbmeta_a"')
48    print('androidboot.slot_suffix = "_a"')
49    print('androidboot.force_normal_boot = "1"')
50    print('androidboot.verifiedbootstate = "green"')
51
52## Main body
53if __name__ == '__main__':
54    main(sys.argv[1:])
55