#!/bin/sh

set -e
set -u
set -x


usage() {
                cat <<END
ERROR: you need to map your idhub git repo volume to docker, suggested volume mapping is:

    volumes:
      - ./IdHub:/opt/idhub
END
                exit 1
}

inject_env_vars() {
        # related https://www.kenmuse.com/blog/avoiding-dubious-ownership-in-dev-containers/
        git config --global --add safe.directory "${idhub_dir}"
        export COMMIT="commit: $(git log --pretty=format:'%h' -n 1)"

        cat > status_data <<END
DOMAIN=${DOMAIN}
END
}

deployment_strategy() {
        # detect if existing deployment (TODO only works with sqlite)
        if [ -f "${idhub_dir}/db.sqlite3" ]; then
                echo "INFO: detected EXISTING deployment"
                ./manage.py makemigrations
                ./manage.py migrate

                # warn admin that it should re-enter password to keep the service working
                ./manage.py send_mail_admins
        else
                # move the migrate thing in docker entrypoint
                #   inspired by https://medium.com/analytics-vidhya/django-with-docker-and-docker-compose-python-part-2-8415976470cc
                echo "INFO detected NEW deployment"
                ./manage.py migrate

                printf "This is DEVELOPMENT/PILOTS_EARLY DEPLOYMENT: including demo hardcoded data\n  creating initial Datas\n" >&2
                ./manage.py initial_datas

                if [ "${OIDC_ORGS:-}" ]; then
                        config_oidc4vp
                fi
        fi
}

_set() {
        key="${1}"
        value="${2}"
        domain="${3}"
        sqlite3 db.sqlite3 "update oidc4vp_organization set ${key}='${value}' where domain='${domain}';"
}

_get() {
        sqlite3 -json db.sqlite3 "select * from oidc4vp_organization;"
}

config_oidc4vp() {
        # populate your config
        local file="${DOMAIN}"
        data="$(_get)"
        echo "${data}" | jq --arg domain "${DOMAIN}" '{ ($domain): .}' > /sharedsecret/${file}

        echo wait the other idhubs to write, this is the only oportunity to sync with other idhubs in the docker compose
        sleep 2
        # get other configs
        for host in /sharedsecret/*; do
                # we are flexible on querying for DOMAIN: the first one based on regex
                target_domain="$(cat "${host}" | jq -r 'keys[0]')"
                if [ "${target_domain}" != "${DOMAIN}" ]; then
                        filtered_data="$(cat "${host}" | jq --arg domain "${DOMAIN}" 'first(.[][] | select(.domain | test ($domain)))')"
                        client_id="$(echo "${filtered_data}" | jq -r '.client_id')"
                        client_secret="$(echo "${filtered_data}" | jq -r '.client_secret')"

                        _set my_client_id ${client_id} ${target_domain}
                        _set my_client_secret ${client_secret} ${target_domain}
                fi
        done
}

main() {
        idhub_dir='/opt/idhub'
        cd "${idhub_dir}"

        if [ ! -f "./manage.py" ]; then
                usage
        fi

        deployment_strategy

        inject_env_vars

        #./manage.py collectstatic

        ./manage.py runserver 0.0.0.0:${PORT}
}

main "${@}"