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

#   configure Certificate Authority (CA) certificate
cat >redis-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 >redis-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 "++ Redis 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 redis-tls-ca.json | \
    @l_prefix@/bin/cfssl-json -bare redis-tls-ca
echo ".. redis-tls-ca.key"
echo ".. redis-tls-ca.crt"

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

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

