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

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

#   configure server certificate
cat >surrealdb-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 "++ SurrealDB 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 surrealdb-tls-ca.json | \
    @l_prefix@/bin/cfssl-json -bare surrealdb-tls-ca
echo ".. surrealdb-tls-ca.key"
echo ".. surrealdb-tls-ca.crt"

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

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

