#!/bin/sh

set -e
# TODO fix the env so configures it to idp, then uncomment this checker
#set -u
# DEBUG
set -x

# this function is similar to the client_id part of config_oidc (devicehub)
oidc_config() {
        # in DEVICEHUB_HOST we remove anything before ://
        client_id_config="/shared/client_id_${SERVER_ID_HOST#*://}"
        CLIENT_ID=
        CLIENT_SECRET=

        # wait that the file generated by the server_id is readable
        while true; do
                if [ -f "${client_id_config}" ]; then
                        CLIENT_ID="$(cat "${client_id_config}" | jq -r '.client_id')"
                        CLIENT_SECRET="$(cat "${client_id_config}" | jq -r '.client_secret')"
                        if [ "${CLIENT_ID}" ] && [ "${CLIENT_SECRET}" ]; then
                                break
                        fi
                fi
                sleep 1
        done
}

populate_env() {
        cat > .env <<END
SECRET_KEY="${SECRET_KEY}"
API_BASE_URL="${API_BASE_URL}"
ALLOWED_HOSTS="${ALLOWED_HOSTS:-.localhost,127.0.0.1}"
STATIC_ROOT="${STATIC_ROOT:-/static/}"
DEBUG="True"
CLIENT_ID="${CLIENT_ID}"
CLIENT_SECRET="${CLIENT_SECRET}"
SERVER_ID_HOST="${SERVER_ID_HOST}"
# path for goautentik idp (TODO)
#OIDC_PROVIDER="${SERVER_ID_HOST}/application/o/authorize"
# path for devicehub idp
OIDC_PROVIDER="${SERVER_ID_HOST}/oauth/authorize"
END
}

main() {
        # go to the same path as the script
        cd "$(dirname ${0})"

        # TODO fix the env so configures it to idp, then uncomment this command:
        #oidc_config

        populate_env

        # move the migrate thing in docker entrypoint
        #   inspired by https://medium.com/analytics-vidhya/django-with-docker-and-docker-compose-python-part-2-8415976470cc
        ./manage.py migrate
        ./manage.py runserver 0.0.0.0:8080
}

main "${@}"