#!/bin/bash

nni=$(who | cut -d' ' -f1 | head -n1)
dsp=$(hostname)
file=/root/tpm/$dsp.csr

if [ -d "/etc/pki/tpm/" ]; then

 :

 else

mkdir -p /etc/pki/tpm/

fi

if [ -d "/etc/pkcs11/modules/" ]; then

 :

 else

mkdir -p /etc/pkcs11/modules/
echo "module: /usr/lib/x86_64-linux-gnu/pkcs11/libtpm2_pkcs11.so.1" >> /etc/pkcs11/modules/tpm.module 

fi

chmod +x /root/tpm/generate_csr.sh
chmod 666 /dev/tpm*

ln -s /usr/lib/x86_64-linux-gnu/libtpm2_pkcs11.so.1 /usr/lib/x86_64-linux-gnu/pkcs11/libtpm2_pkcs11.so.1

SYSTEMD_EDITOR=tee systemctl edit wpa_supplicant <<EOF
[Service]
Environment="pkcs11_module_path=/usr/lib/x86_64-linux-gnu/pkcs11/libtpm2_pkcs11.so.1"
Environment="TPM2_PKCS11_STORE=/root/tpm/tmp"
EOF

if [ -f "/usr/share/p11-kit/modules/tpm2_pkcs11.module" ]; then

 :

else

cat << EOF >> "/usr/share/p11-kit/modules/tpm2_pkcs11.module"
module: libtpm2_pkcs11.so
critical: no

EOF

fi

if [ -f "/root/tpm/$dsp.csr" ]; then

	exit 0

fi

cd /root/tpm/ && /bin/bash /root/tpm/generate_csr.sh 2> /etc/pki/tpm/tpm.log

exit 0
