#!/usr/bin/python3
"""Skip ZFS startup until its driver can be authorised by Secure Boot.

Exit 1 is a normal systemd ExecCondition skip, not a failed boot service.
This does not enrol keys, load modules or change firmware security settings.
"""
from pathlib import Path
import os
import subprocess
import sys


def ready(*,efivars=Path('/sys/firmware/efi/efivars'),
          certificate=Path('/usr/share/brimstone-core/zfs-signing.der')):
    secure=next(efivars.glob('SecureBoot-*'),None)
    if secure is None or secure.read_bytes()[-1:] != b'\x01':
        return True
    if not certificate.is_file():
        return False
    try:
        result=subprocess.run(['mokutil','--test-key',str(certificate)],
                              capture_output=True,text=True,timeout=5,check=False,
                              env={**os.environ,'LC_ALL':'C'})
        # mokutil 0.7.2 uses 0 for "is not enrolled" and 1 for an enrolled
        # certificate. Require both its positive message and expected status.
        return result.returncode==1 and ' is already enrolled' in result.stdout.lower()
    except (OSError,subprocess.TimeoutExpired):
        return False


if __name__=='__main__':
    sys.exit(0 if ready() else 1)
