#!/usr/bin/python3

import ctypes
import ctypes.util
import glob
import os
import shutil
import subprocess
import sys


if shutil.which('nss-policy-check') is None:
    print('nss-policy-check not found, skipping check', file=sys.stderr)
    sys.exit(0)


# Cannot validate with pre-3.59 NSS that doesn't know ECDSA/RSA-PSS/RSA-PKCS
# identifiers yet. Checking for 3.66 because that's what we'll have in 8.5.
try:
    nss = ctypes.CDLL(ctypes.util.find_library('nss3'))
    if not nss.NSS_VersionCheck(b'3.66'):
        print('Skipping nss-policy-check verification '
              'due to nss being older than 3.66', file=sys.stderr)
        sys.exit(0)
except AttributeError:
    print('Cannot determine nss version with ctypes, hoping for >=3.59',
          file=sys.stderr)


print('Checking the NSS configuration')

for policy_path in glob.glob('tests/outputs/*-nss.txt'):
    policy = os.path.basename(policy_path)[:-len('-nss.txt')]
    print(f'Checking policy {policy}')
    if policy not in ('EMPTY', 'GOST-ONLY'):
        p = subprocess.Popen(['nss-policy-check', policy_path],
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        output, _ = p.communicate()
        if p.wait():
            print(f'Error in NSS policy for {policy}')
            print(f'NSS policy for {policy}:', file=sys.stderr)
            with open(policy_path) as policy_file:
                shutil.copyfileobj(policy_file, sys.stderr)
                sys.stderr.write('\n')
            print('nss-policy-check error:', file=sys.stderr)
            print(output.decode(), file=sys.stderr)
            sys.exit(1)
