#!/bin/bash -e
# Copyright (C) 2022 Simo Sorce <simo@redhat.com>
# SPDX-License-Identifier: Apache-2.0

source "${TESTSSRCDIR}/helpers.sh"

title PARA "Check we can fetch certifiatce objects"

ossl '
x509 -in ${CRTURI} -subject -out ${TMPPDIR}/crt-subj.txt'
DATA=$(sed -e 's/\ =\ /=/g' "${TMPPDIR}/crt-subj.txt")
CHECK="subject=O=PKCS11 Provider, CN=My Test Cert"
if [[ ! ${DATA} =~ ${CHECK} ]]; then
    echo "Cert not found looking for ${CHECK}"
    exit 1
fi

ossl '
x509 -in ${ECCRTURI} -subject -out ${TMPPDIR}/eccrt-subj.txt'
DATA=$(sed -e 's/\ =\ /=/g' "${TMPPDIR}/eccrt-subj.txt")
CHECK="subject=O=PKCS11 Provider, CN=My EC Cert"
if [[ ! ${DATA} =~ ${CHECK} ]]; then
    echo "Cert not found looking for ${CHECK}"
    exit 1
fi

title PARA "Use storeutl command to match specific certs via params"

SUBJECTS=("/O=PKCS11 Provider/CN=My Test Cert"
          "/O=PKCS11 Provider/CN=My EC Cert"
          "/O=PKCS11 Provider/CN=My Peer EC Cert"
          "/CN=Issuer")

for subj in "${SUBJECTS[@]}"; do
ossl '
storeutl -certs -subject "${subj}"
                -out ${TMPPDIR}/storeutl-crt-subj.txt
                pkcs11:type=cert'
DATA=$(cat "${TMPPDIR}/storeutl-crt-subj.txt")
if [[ ! ${DATA} =~ "Total found: 1" ]]; then
    echo "Cert not found matching by subject=${subj}"
    exit 1
fi
done

exit 0
