#!/bin/bash
CERTS_FOLDER="/etc/nginx/certs"
cd $CERTS_FOLDER

VAULT_ADDR="http://$VAULT_HOSTNAME:$VAULT_PORT"
VAULT_TOKEN=$VAULT_ACCESS_TOKEN

curl  -k -retry 30 \
    --retry-all-errors \
    --connect-timeout 5 \
    --max-time 10 \
    --retry-delay 10 \
    --retry-max-time 300 \
    --header "X-Vault-Token: $VAULT_TOKEN" \
    --request GET "$VAULT_ADDR/v1/secret/data/ca" 2>/dev/null | jq -r '.data.data.ca' -j > $CERTS_FOLDER/ca.crt

openssl verify -CAfile $CERTS_FOLDER/ca.crt $CERTS_FOLDER/ca.crt

curl  -k -retry 30 \
    --retry-all-errors \
    --connect-timeout 5 \
    --max-time 10 \
    --retry-delay 10 \
    --retry-max-time 300 \
    --header "X-Vault-Token: $VAULT_TOKEN" \
    --request GET "$VAULT_ADDR/v1/secret/data/server_cert" 2>/dev/null | jq -r '.data.data.cert' -j > $CERTS_FOLDER/server.crt

curl  -k -retry 30 \
    --retry-all-errors \
    --connect-timeout 5 \
    --max-time 10 \
    --retry-delay 10 \
    --retry-max-time 300 \
    --header "X-Vault-Token: $VAULT_TOKEN" \
    --request GET "$VAULT_ADDR/v1/secret/data/server_cert/private" 2>/dev/null | jq -r '.data.data.key' -j > $CERTS_FOLDER/server.key

LOG_LEVEL=$(echo "${LOG_LEVEL}" | tr '[:upper:]' '[:lower:]')

case "$LOG_LEVEL" in
  critical)
    LOG_LEVEL="crit"
    ;;
  fatal)
    LOG_LEVEL="error"
    ;;
  notset)
    LOG_LEVEL="info"
    ;;
esac

envsubst '$LOG_LEVEL' < /etc/nginx/nginx.conf > /etc/nginx/nginx.conf.tmp
mv /etc/nginx/nginx.conf.tmp /etc/nginx/nginx.conf
nginx