#!/bin/sh
##
##  vault-tls.sh -- utility for Vault to generate SSL/TLS private-key/certificate files
##  Copyright (c) 2016 Ralf S. Engelschall <rse@engelschall.com>
##

#   configure Certificate Authority (CA) certificate
cat >vault-tls-ca.json <<EOT
{
    "key": {
        "algo": "rsa",
        "size": 4096
    },
    "names": [{
        "OU": "Certificate Authority",
        "O":  "Example, Inc"
    }]
}
EOT

#   configure server certificate
cat >vault-tls-sv.json <<EOT
{
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "CN": "server.example.com",
    "hosts": [ "server.example.com", "127.0.0.1" ],
    "names": [{
        "OU": "Server Administration",
        "O":  "Example, Inc"
    }]
}
EOT

#   preparation
echo "++ Vault SSL/TLS RSA private-key and X.509 certificate generation"

#   generate Certificate Authority (CA) private-key/certificate pair
echo "-- generate Certificate Authority (CA) private-key/certificate pair"
@l_prefix@/bin/cfssl genkey -loglevel 3 -initca vault-tls-ca.json | \
    @l_prefix@/bin/cfssl-json -bare vault-tls-ca
echo ".. vault-tls-ca.key"
echo ".. vault-tls-ca.crt"

#   generate server private-key/certificate pair
echo "-- generate server private-key/certificate pair"
@l_prefix@/bin/cfssl gencert -loglevel 3 -ca vault-tls-ca.crt -ca-key vault-tls-ca.key vault-tls-sv.json | \
    @l_prefix@/bin/cfssl-json -bare vault-tls-sv
echo ".. vault-tls-sv.key"
echo ".. vault-tls-sv.crt"

#   cleanup
chown @l_rusr@:@l_rgrp@ vault-tls-ca.key vault-tls-ca.crt vault-tls-sv.key vault-tls-sv.crt
chmod 600 vault-tls-ca.key vault-tls-sv.key
chmod 644 vault-tls-ca.crt vault-tls-sv.crt
rm -f vault-tls-ca.csr vault-tls-ca.json
rm -f vault-tls-sv.csr vault-tls-sv.json

