#!/bin/bash -x

/usr/bin/wait_on_postgres.py

# Generating /var/lib/pulp/static at runtime rather than at container build time
# facilitates all of /var/lib/pulp being a separate volume.
django-admin collectstatic --noinput

# Get list of installed plugins via pip
# Assumes they are all named like "pulp-file" -> "file", with no 2nd dash.
# (Was previously needed when we ran `django-admin makemigrations`)
# PLUGINS=$(pip list | awk -F '[[:space:]]+|[-]' '/pulp-/{printf $2 " " }')

django-admin migrate --noinput
django-admin migrate auth --noinput

bash +x

if [ -n "${PULP_SIGNING_KEY_FINGERPRINT}" ]; then
    django-admin add-signing-service "${SIGNING_SERVICE}" /var/lib/pulp/scripts/collection_sign.sh "${PULP_SIGNING_KEY_FINGERPRINT}"
fi

ADMIN_PASSWORD_FILE=/etc/pulp/pulp-admin-password
if [[ -f "$ADMIN_PASSWORD_FILE" ]]; then
   echo "pulp admin can be initialized."
   PULP_ADMIN_PASSWORD=$(cat $ADMIN_PASSWORD_FILE)
fi

if [ -n "${PULP_ADMIN_PASSWORD}" ]; then
    django-admin reset-admin-password --password "${PULP_ADMIN_PASSWORD}"
fi
bash -x

PULP_GUNICORN_TIMEOUT=${PULP_GUNICORN_TIMEOUT:-90}
PULP_API_WORKERS=${PULP_API_WORKERS:-1}

mkdir -p /var/lib/pulp/media \
         /var/lib/pulp/assets \
         /var/lib/pulp/tmp

# NOTE: Due to the Linux dual-stack functionality, this will listen on both IPv4
# IPv6, even though netstat may seem to indicate it is IPv6 only.
# Due to containers using network namespaces, even if the host has this disabled
# with /proc/sys/net/ipv6/bindv6only=1, the container will still have
# it enabled with /proc/sys/net/ipv6/bindv6only=0 .
exec gunicorn --bind '[::]:24817' pulpcore.app.wsgi:application \
--timeout "${PULP_GUNICORN_TIMEOUT}" \
--workers "${PULP_API_WORKERS}"
