#!/usr/bin/env bash

set -eux

tests_dir=$(dirname "$(realpath $0)")
cfg_dir=$HOME/.config/nitrokey
mkdir -p $cfg_dir
trap 'rm -f "${cfg_dir}/p11nethsm.conf"' EXIT

# Test: Verify p11-kit can find and load the module.
# Ensures the C_Initialize API and config parsing work.
# No device is connected, but still enough to test module loading.

p11nethsm_log=$(mktemp --suffix=.log -t autopkgtest-p11nethsm-XXXX)
p11_kit_modules=$(mktemp --suffix=.txt -t autopkgtest-p11-kit-modules-XXXX)

cat << EOF > "${cfg_dir}/p11nethsm.conf"
log_level: Trace
log_file: ${p11nethsm_log}
syslog_socket: /dev/null
slots:
  - label: NetHSM
    description: NetHSM - not connected
    operator:
      username: "operator"
    administrator:
      username: "admin"
    instances:
      - url: "https://"
    retries:
      count: 0
      delay_seconds: 0
    timeout_seconds: 0
EOF

p11-kit list-modules > $p11_kit_modules

grep "module: nethsm_pkcs11" $p11_kit_modules
grep "uri: pkcs11:library-description=Nitrokey%20NetHsm%20PKCS%2311%20library;library-manufacturer=Nitrokey" $p11_kit_modules
grep "library-description: Nitrokey NetHsm PKCS#11 library" $p11_kit_modules
grep "library-manufacturer: Nitrokey" $p11_kit_modules
grep "library-version: 2.0" $p11_kit_modules
grep "Loaded config file at: ${cfg_dir}/p11nethsm.conf" $p11nethsm_log
grep "Loaded configuration with 1 slots" $p11nethsm_log
grep "C_Initialize() called" $p11nethsm_log
