#!@l_bash@
##
##  sftpgo-cred -- SFTPgo credential generation
##

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

#
#   ==== STEP 1: SSH/SFTP credentials =====
#

#   initialize SSH host keys
@l_prefix@/bin/ssh-keygen -t rsa -b 2048 \
    -f sftpgo.ssh.id_rsa -N '' -C "$1" >/dev/null 2>&1
@l_prefix@/bin/ssh-keygen -t ecdsa -b 521 \
    -f sftpgo.ssh.id_ecdsa -N '' -C "$1" >/dev/null 2>&1

#
#   ==== STEP 2: HTTPS/WebDAV credentials =====
#

#   generate CA certificate/key pair
(   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 sftpgo.tls-ca
rm -f sftpgo.tls-ca.csr
chmod 600 sftpgo.tls-ca.key
chmod 644 sftpgo.tls-ca.crt
(   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 "}"
) >sftpgo.tls-ca.json
chmod 644 sftpgo.tls-ca.json

#   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 sftpgo.tls-ca.crt \
    -ca-key sftpgo.tls-ca.key \
    -config sftpgo.tls-ca.json \
    -profile=peer - | \
    @l_prefix@/bin/cfssl-json \
        -bare sftpgo.tls-sv
rm -f sftpgo.tls-sv.csr
chmod 600 sftpgo.tls-sv.key
chmod 644 sftpgo.tls-sv.crt

