#!/usr/bin/python3
import subprocess
import os
import sys

if not os.path.exists("/boot/grub/grub.cfg"):
    print("Your system does not seem to have grub, this test cannot work", file=sys.stderr)
    sys.exit(77)

with open("/boot/grub/grub.cfg") as f:
    grub_cfg = f.read()

tboot_count = grub_cfg.count("Loading tboot ")
if tboot_count == 0:
    print("Your system does not seem to tboot entries in grub.cfg, this test cannot work", file=sys.stderr)
    sys.exit(77)

with open("/boot/autopkgtest_dummy_SINIT_123", "wb+") as f:
    f.write(b"dummy sinit file")

subprocess.check_call(["update-grub2"], stderr=subprocess.DEVNULL)

with open("/boot/grub/grub.cfg") as f:
    grub_cfg = f.read()

tboot_count = grub_cfg.count("Loading tboot ")
sinit_count = grub_cfg.count("Loading sinit autopkgtest_dummy_SINIT_123")

# Check that the workaround described in debian/grub-tboot really works and loads each sinit module twice.
if sinit_count != 2 * tboot_count:
    print(f"grub.cfg seems to have {sinit_count} references to sinit modules and {tboot_count} references to tboot: {grub_cfg}", file=sys.stderr)
    sys.exit(1)
else:
    sys.exit(0)
