#!@l_bash@
##
##  teleport-tls -- Teleport Server TLS certificate/key generation
##

cd @l_prefix@/etc/teleport || exit $?

#   generate CA certificate/key pair
if [ ! -f ca.crt ]; then
    (   echo "{"
        echo "    \"key\": {"
        echo "        \"algo\": \"rsa\","
        echo "        \"size\": 4096"
        echo "    },"
        echo "    \"ca\": {"
        echo "        \"expiry\": \"87600h\","
        echo "        \"pathlen\": 1"
        echo "    },"
        echo "    \"CN\": \"CA\","
        echo "    \"names\": ["
        echo "        {"
        echo "            \"OU\": \"Certificate Authority\""
        echo "        }"
        echo "    ]"
        echo "}"
    ) | \
    @l_prefix@/bin/cfssl genkey -loglevel=4 -initca - | \
    @l_prefix@/bin/cfssl-json -bare ca
    rm -f ca.csr
    chmod 600 ca.key
    chmod 644 ca.crt
    chown @l_rusr@:@l_rgrp@ ca.crt
    chown @l_rusr@:@l_rgrp@ ca.key
    (   echo "{"
        echo "    \"signing\": {"
        echo "        \"profiles\": {"
        echo "            \"peer\": {"
        echo "                \"expiry\": \"87600h\","
        echo "                \"usages\": ["
        echo "                    \"signing\","
        echo "                    \"key encipherment\","
        echo "                    \"server auth\","
        echo "                    \"client auth\""
        echo "                ]"
        echo "            }"
        echo "        }"
        echo "    }"
        echo "}"
    ) >ca.json
    chmod 644 ca.json
    chown @l_rusr@:@l_rgrp@ ca.json
fi

#   generate server certificate/key pair
(   echo "{"
    echo "    \"key\": {"
    echo "        \"algo\": \"rsa\","
    echo "        \"size\": 4096"
    echo "    },"
    echo "    \"CN\": \"$1\","
    echo "    \"hosts\": ["
    i=0
    for host in "$@"; do
        echo -n "        \"$host\""
        i=`expr $i + 1`
        if [ $i -lt $# ]; then
            echo -n ","
        fi
        echo ""
    done
    echo "    ]"
    echo "}"
) | \
@l_prefix@/bin/cfssl gencert -loglevel=4 -ca ca.crt -ca-key ca.key -config ca.json -profile=peer - | \
@l_prefix@/bin/cfssl-json -bare server
rm -f server.csr
chmod 600 server.key
chmod 644 server.crt
chown @l_rusr@:@l_rgrp@ server.crt
chown @l_rusr@:@l_rgrp@ server.key

