#!/bin/bash
#
# selftest.sh — throwaway end-to-end CA loop in /tmp [#697]
# TDD gate for the CA tooling: init -> issue -> verify chain -> negative check.
#
set -euo pipefail
T="$(mktemp -d)"
trap 'rm -rf "$T"' EXIT

bash "$(dirname "$0")/ca-init.sh" "$T/root" "$T/int" > /dev/null
if [ ! -s "$T/root/root.key" ] || [ ! -s "$T/int/intermediate.crt" ]; then echo "FAIL: init"; exit 1; fi

INT_DIR="$T/int" bash "$(dirname "$0")/issue-cert.sh" test.knel.net "DNS:test.knel.net,IP:10.0.0.1" > /dev/null
openssl verify -CAfile "$T/root/root.crt" "$T/int/intermediate.crt" > /dev/null
openssl x509 -in "$T/int/certs/test.knel.net.crt" -noout -ext subjectAltName | grep -q "test.knel.net"
openssl x509 -in "$T/int/certs/test.knel.net.fullchain" -noout | head -1 > /dev/null
echo "SELFTEST PASS: root->intermediate->leaf chain verified with SANs"
