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

#   configure Certificate Authority (CA) certificate
cat >valkey-tls-ca.json <<EOT
{
    "key": {
        "algo": "rsa",
        "size": 4096
    },
    "names": [{
        "C":  "US",
        "ST": "California",
        "L":  "San Francisco",
        "OU": "Certificate Authority",
        "O":  "Example, Inc"
    }]
}
EOT

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

#   preparation
echo "++ ValKey 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 valkey-tls-ca.json | \
    @l_prefix@/bin/cfssl-json -bare valkey-tls-ca
echo ".. valkey-tls-ca.key"
echo ".. valkey-tls-ca.crt"

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

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

