#!@l_bash@
##
##  spire-ca -- SPIRE CA certificate/key generation
##

domain="${1-example.com}"

cd @l_prefix@/etc/spire || exit $?

(   echo "[req]"
    echo "prompt                 = no"
    echo "distinguished_name     = req_distinguished_name"
    echo "x509_extensions        = req_v3"
    echo ""
    echo "[req_distinguished_name]"
    echo "CN                     = TD-CA"
    echo "OU                     = Trust Domain Certificate Authority"
    echo ""
    echo "[req_v3]"
    echo "subjectKeyIdentifier   = hash"
    echo "authorityKeyIdentifier = keyid:always, issuer:always"
    echo "basicConstraints       = critical, CA:TRUE, pathlen:1"
    echo "keyUsage               = critical, cRLSign, digitalSignature, keyCertSign, keyEncipherment, dataEncipherment"
    echo "subjectAltName         = @alt_names"
    echo ""
    echo "[alt_names]"
    echo "URI.1                  = spiffe://${domain}"
    echo "DNS.1                  = ${domain}"
) >spire-ca.cnf

@l_prefix@/bin/openssl ecparam -name secp384r1 -genkey | openssl ec -out spire-ca.key
@l_prefix@/bin/openssl req -x509 -days 3650 -key spire-ca.key -out spire-ca.crt -config spire-ca.cnf

chmod 600 spire-ca.key
chmod 644 spire-ca.crt
chown @l_rusr@:@l_rgrp@ spire-ca.crt
chown @l_rusr@:@l_rgrp@ spire-ca.key

rm -f spire-ca.cnf

