#!/bin/bash
# Generates test certificates for localhost so tls can be tested

base_dir=$(dirname $(dirname $0))

cert_dir="${base_dir}/certs/"

if [ ! -d "${cert_dir}" ]; then
    mkdir -p ${cert_dir}
fi

if [ ! -f "${cert_dir}/ca.key" ]; then
    openssl genrsa -out ${cert_dir}/ca.key 4096

    openssl req \
        -new \
        -x509 \
        -nodes \
        -days 3650 \
        -key ${cert_dir}/ca.key \
        -out ${cert_dir}/ca.cert \
        -subj '/O=Example CA/'
fi

if [ -f /etc/pki/tls/openssl.cnf ]; then
    openssl_cnf="/etc/pki/tls/openssl.cnf"
elif [ -f /etc/ssl/openssl.cnf ]; then
    openssl_cnf="/etc/ssl/openssl.cnf"
else
    echo "No openssl.cnf"
    exit 1
fi

for name in localhost; do
    openssl genrsa -out ${cert_dir}/${name}.key 4096

    openssl req \
        -new \
        -key ${cert_dir}/${name}.key \
        -out ${cert_dir}/${name}.csr \
        -subj "/O=Example CA/CN=${name}/" \
        -reqexts SAN \
        -config <(cat ${openssl_cnf} \
            <(printf "[SAN]\nsubjectAltName=DNS:${name}"))

    openssl x509 \
        -req \
        -in ${cert_dir}/${name}.csr \
        -CA ${cert_dir}/ca.cert \
        -CAkey ${cert_dir}/ca.key \
        -CAcreateserial \
        -out ${cert_dir}/${name}.cert \
        -days 28 \
        -extfile <(cat ${openssl_cnf} \
            <(printf "[SAN]\nsubjectAltName=DNS:${name}")) \
        -extensions SAN
done

openssl dhparam -out ${cert_dir}/dhparam4096.pem

chmod 644 ${cert_dir}/*.{cert,key,pem}
