# Create CA private key and certificate
openssl genrsa -out "$AUTOPKGTEST_TMP/ca.key.priv.pem" 2048
cat >"$AUTOPKGTEST_TMP/ca.openssl.cnf" <<EOF
[ req ]
distinguished_name = req_dn
string_mask = utf8only
prompt = no
x509_extensions = req_ext

[ req_dn ]
commonName = ktls-utils test CA

[ req_ext ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints = critical, CA:true
EOF
openssl req -new -key "$AUTOPKGTEST_TMP/ca.key.priv.pem" \
	-utf8 -nodes -batch -x509 \
        -outform PEM -out "$AUTOPKGTEST_TMP/ca.x509.pem" \
        -config "$AUTOPKGTEST_TMP/ca.openssl.cnf"

sed -i '/^\[authenticate\.client\]/,$ { /=/d }' \
    /etc/tlshd.conf

for role in server client; do
    # Create private key and certificate for role
    openssl genrsa -out "$AUTOPKGTEST_TMP/$role.key.priv.pem" 2048
    cat >"$AUTOPKGTEST_TMP/$role.openssl.cnf" <<EOF
[ req ]
distinguished_name = req_dn
string_mask = utf8only
prompt = no
x509_extensions = req_ext

[ req_dn ]
commonName = $role.internal

[ req_ext ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints = critical, CA:false
extendedKeyUsage = critical, ${role}Auth
EOF
    openssl req -new -key "$AUTOPKGTEST_TMP/$role.key.priv.pem" \
	    -out "$AUTOPKGTEST_TMP/$role.req.pem" \
            -config "$AUTOPKGTEST_TMP/$role.openssl.cnf"
    openssl req -in "$AUTOPKGTEST_TMP/$role.req.pem" \
	    -copy_extensions copy \
	    -CA "$AUTOPKGTEST_TMP/ca.x509.pem" \
	    -CAkey "$AUTOPKGTEST_TMP/ca.key.priv.pem" \
	    -utf8 -nodes -batch -x509 \
            -outform PEM -out "$AUTOPKGTEST_TMP/$role.x509.pem"

    # Update tlshd.conf
    sed -i '/^\[authenticate\.'$role'\]/a\
x509.truststore='"$AUTOPKGTEST_TMP/ca.x509.pem"'\
x509.certificate='"$AUTOPKGTEST_TMP/$role.x509.pem"'\
x509.private_key='"$AUTOPKGTEST_TMP/$role.key.priv.pem" \
	/etc/tlshd.conf
done

# Make server name resolvable
if ! grep -qw 'server\.internal' /etc/hosts; then
    cat >>/etc/hosts <<EOF
::1	server.internal
EOF
fi

# Restart tlshd with new config
systemctl restart tlshd
