#!/bin/bash
#
# YACHT (Yet Another CA How To) Placed in public domain. RLamb 2019
#
read -p "CKA_ID: " mkid
./hcardshow > $0.tmp
kref=""
keyref=""
kid=""
while [ "1" ]; do
  read a b c d e
  if [ $? -ne 0 ]; then break; fi
  if [ -z "$a" ]; then
    if [ "$keyref" ]; then
      # echo "$kid $keyref";
      if [ "$kid" = "$mkid" -a "$keyref" != "0" ]; then
        echo "$mkid -> $keyref"
	kref="$keyref"
        break
      fi
    fi
    keyref=""
    continue;
  fi
  if [ "$a" = "Key" -a "$b" = "ref" ]; then
    keyref="$d"
  fi
  if [ "$a" = "ID" -a "$b" = ":" ]; then
    kid="$c"
  fi
done < $0.tmp
rm -rf $0.tmp
if [ -z "$kref" ]; then
  echo "$mkid CKA_ID does not exist in HSM. Check with hcardshow."
  exit 0
fi
read -s -p "HSM PIN: " PKCS11_LIBRARY_PIN
echo ""
sc-hsm-tool --wrap-key "$mkid"".wrap" --key-reference $kref --pin $PKCS11_LIBRARY_PIN
