#!/bin/bash -e
function log {
    printf '{"event": "%s", "level": "info", "logger": "bootstrap"}\n' "$@" > /dev/stderr
}

function wait_for_db {
    python -m lifecycle.wait_for_db
    log "Bootstrap completed"
}

function check_if_root {
    if [[ $EUID -ne 0 ]]; then
        log "Not running as root, disabling permission fixes"
        $1
        return
    fi
    SOCKET="/var/run/docker.sock"
    GROUP="authentik"
    if [[ -e "$SOCKET" ]]; then
        # Get group ID of the docker socket, so we can create a matching group and
        # add ourselves to it
        DOCKER_GID=$(stat -c '%g' $SOCKET)
        # Ensure group for the id exists
        getent group $DOCKER_GID || groupadd -f -g $DOCKER_GID docker
        usermod -a -G $DOCKER_GID authentik
        # since the name of the group might not be docker, we need to lookup the group id
        GROUP_NAME=$(getent group $DOCKER_GID | sed 's/:/\n/g' | head -1)
        GROUP="authentik:${GROUP_NAME}"
    fi
    # Fix permissions of backups and media
    chown -R authentik:authentik /media /certs
    exec chpst -u authentik:$GROUP env HOME=/authentik $1
}

MODE_FILE="/tmp/authentik-mode"

if [[ "$1" == "server" ]]; then
    wait_for_db
    echo "server" > $MODE_FILE
    python -m lifecycle.migrate
    if [[ ! -z "${AUTHENTIK_BOOTSTRAP_PASSWORD}" || ! -z "${AUTHENTIK_BOOTSTRAP_TOKEN}" ]]; then
        python -m manage bootstrap_tasks
    fi
    exec /authentik-proxy
elif [[ "$1" == "worker" ]]; then
    wait_for_db
    echo "worker" > $MODE_FILE
    check_if_root "celery -A authentik.root.celery worker -Ofair --max-tasks-per-child=1 --autoscale 3,1 -E -B -s /tmp/celerybeat-schedule -Q authentik,authentik_scheduled,authentik_events"
elif [[ "$1" == "bash" ]]; then
    /bin/bash
elif [[ "$1" == "test-all" ]]; then
    pip install --no-cache-dir -r /requirements-dev.txt
    touch /unittest.xml
    chown authentik:authentik /unittest.xml
    check_if_root "python -m manage test authentik"
elif [[ "$1" == "healthcheck" ]]; then
    mode=$(cat $MODE_FILE)
    if [[ $mode == "server" ]]; then
        exec curl --user-agent "goauthentik.io lifecycle Healthcheck" -I http://localhost:9000/-/health/ready/
    elif [[ $mode == "worker" ]]; then
        exec celery -A authentik.root.celery inspect ping -d celery@$HOSTNAME --timeout 5 -j
    fi
elif [[ "$1" == "dump_config" ]]; then
    exec python -m authentik.lib.config
elif [[ "$1" == "debug" ]]; then
    exec sleep infinity
else
    exec python -m manage "$@"
fi
