#!/bin/sh
# Entrypoint for Docker Container

export PROXY_CONFIG_FILE=${CONFIG:-'/etc/gatekeeper/gatekeeper.conf'}

CLIENT_ID=${CLIENT_ID}
CLIENT_SECRET=${CLIENT_SECRET}
UPSTREAM_URL=${UPSTREAM_URL}
REDIRECTION_URL=${REDIRECTION_URL}

ENCRYPTION_KEY=${ENCRYPTION_KEY:-'SjjCbZzUcYmxQFttEh3KJnZaEPCb6iuB'}
DISCOVERY_URL=${DISCOVERY_URL:-'https://auth.pirati.cz/auth/realms/pirati'}
LISTEN=${LISTEN:-':3000'}


CERTIFICATE_SUBJ=${CERTIFICATE_SUBJ:-'/C=CZ/ST=CZ/L=Praha/O=Pirati/OU=TO/CN=gatekeeper'}

if [ -s /etc/gatekeeper/ssl.crt ] || [ -s /etc/gatekeeper/cert.pem ] || [ -s /etc/gatekeeper/key.pem ] || [ -n "${SKIP_SSL_GENERATE}" ]; then
    echo "Skipping SSL certificate generation"
else
    echo "Generating self-signed certificate"

    cd /etc/gatekeeper

    # Generating signing SSL private key
    openssl genrsa -des3 -passout pass:xxxx -out key.pem 2048
    # Removing passphrase from private key
    cp key.pem key.pem.orig
    openssl rsa -passin pass:xxxx -in key.pem.orig -out key.pem
    # Generating certificate signing request
    openssl req -new -key key.pem -out cert.csr -subj "${CERTIFICATE_SUBJ}"
    # Generating self-signed certificate
    openssl x509 -req -days 3650 -in cert.csr -signkey key.pem -out cert.pem
fi

echo "# GATEKEEPER CONFIG 
client-id: ${CLIENT_ID}
client-secret: ${CLIENT_SECRET}
discovery-url: ${DISCOVERY_URL}
encryption-key: ${ENCRYPTION_KEY} 
enable-default-deny: true
listen: ${LISTEN}
upstream-url: ${UPSTREAM_URL} 

tls-cert: /etc/gatekeeper/cert.pem
tls-private-key: /etc/gatekeeper/key.pem 
cors-origins:
- '*'
cors-methods:
- GET
- POST
resources:
${RESOURCES}
" > /etc/gatekeeper/gatekeeper.conf

exec "$@" 
