#!/bin/bash

PEMFILE="$1"

if [ -z "${PEMFILE}" ]; then
    echo "Missing pem file"
    exit 1
fi

HOSTNAME=$(hostname)
HOSTIP=$(hostname -I | awk '{print $2}')
cat << EOF > "${PEMFILE}.conf"
[req]
default_bits  = 2048
distinguished_name = req_distinguished_name
req_extensions = req_ext
x509_extensions = v3_req
prompt = no

[req_distinguished_name]
O=system:nodes
CN=system:node:${HOSTNAME}

[v3_req]
subjectAltName = @alt_names

[req_ext]
subjectAltName = @alt_names

[alt_names]
DNS.1 = ${HOSTNAME}
IP.1 = ${HOSTIP}
EOF

openssl ec -in "${PEMFILE}" -out "${PEMFILE}.key"
openssl req -new -key "${PEMFILE}.key" -out "${PEMFILE}.csr" -config "${PEMFILE}.conf" -copy_extensions copy
rm "${PEMFILE}.crt"
openssl x509 -req -days 6666 -in "${PEMFILE}.csr" -CA signer.crt -CAkey signer.key -CAcreateserial -out "${PEMFILE}.crt" -copy_extensions copy
cat "${PEMFILE}.key" "${PEMFILE}.crt" > "${PEMFILE}-new"
openssl x509 -in "${PEMFILE}-new" -text
