#!/bin/sh
##
##  cockroach-cert.sh -- CockroachDB Certificate Generation Utility
##

usage () {
    echo "USAGE: cockroach-cert ca" 1>&2
    echo "USAGE: cockroach-cert server <host-name> [<ip-address> ...]" 1>&2
    echo "USAGE: cockroach-cert client <user-name>" 1>&2
    exit 1
}
if [ $# -lt 1 ]; then
    usage
fi
cmd="$1"
shift
if [ ".$cmd" = .ca ]; then
    if [ $# -ne 0 ]; then
        usage
    fi
    echo "++ generating CA certificate/key pair"
    echo "-- generating: @l_prefix@/etc/cockroach/certs/ca.crt"
    echo "-- generating: @l_prefix@/etc/cockroach/certs/ca.key"
    su - @l_rusr@ -c \
        "@l_prefix@/bin/cockroach cert create-ca \
            --overwrite \
            --certs-dir=@l_prefix@/etc/cockroach/certs \
            --ca-key=@l_prefix@/etc/cockroach/certs/ca.key"
elif [ ".$cmd" = .server ]; then
    if [ $# -lt 1 ]; then
        usage
    fi
    echo "++ generating server certificate/key pair"
    echo "-- generating: @l_prefix@/etc/cockroach/certs/node.crt"
    echo "-- generating: @l_prefix@/etc/cockroach/certs/node.key"
    su - @l_rusr@ -c \
        "@l_prefix@/bin/cockroach cert create-node \
            --overwrite \
            --certs-dir=@l_prefix@/etc/cockroach/certs \
            --ca-key=@l_prefix@/etc/cockroach/certs/ca.key \
            $*"
elif [ ".$cmd" = .client ]; then
    if [ $# -lt 1 ]; then
        usage
    fi
    username="$1"
    shift
    echo "++ generating client certificate/key pair"
    echo "-- generating: @l_prefix@/etc/cockroach/certs/client.$username.crt"
    echo "-- generating: @l_prefix@/etc/cockroach/certs/client.$username.key"
    su - @l_rusr@ -c \
        "@l_prefix@/bin/cockroach cert create-client \
            --overwrite \
            --certs-dir=@l_prefix@/etc/cockroach/certs \
            --ca-key=@l_prefix@/etc/cockroach/certs/ca.key \
            $username $*"
fi

