#!/bin/sh
set -ev

# Volumes
POSTGRES_DATA="${VOLUMES_DIR}/pandora/postgres_data"
RABBITMQ_DATA="${VOLUMES_DIR}/pandora/rabbitmq_data"
PANDORA_CONF="${VOLUMES_DIR}/pandora/pandora_conf"
PANDORA_DATA="${VOLUMES_DIR}/pandora/pandora_data"

# Create Postgres instance
install -o 105432 -g 105432 -m 700 -d ${POSTGRES_DATA}
spoc-container exec pandora-postgres -- initdb -D /var/lib/postgresql

# Configure Postgres
install -o 105432 -g 105432 -m 600 postgres_data/postgresql.conf ${POSTGRES_DATA}/postgresql.conf
install -o 105432 -g 105432 -m 600 postgres_data/pg_hba.conf ${POSTGRES_DATA}/pg_hba.conf

# Create PostgreSQL user and database
export PANDORA_PWD=$(head -c 18 /dev/urandom | base64 | tr -d '+/=')
spoc-container start pandora-postgres
envsubst <createdb.sql | spoc-container exec pandora-postgres -- psql

# Create RabbitMQ directory structure
install -o 105672 -g 105672 -m 750 -d ${RABBITMQ_DATA}

# Configure RabbitMQ virtualhost
export PANDORA_RABBIT_PWD=$(head -c 18 /dev/urandom | base64 | tr -d '+/=')
spoc-container start pandora-rabbitmq
spoc-container exec pandora-rabbitmq -- rabbitmqctl add_user pandora ${PANDORA_RABBIT_PWD}
spoc-container exec pandora-rabbitmq -- rabbitmqctl add_vhost /pandora
spoc-container exec pandora-rabbitmq -- rabbitmqctl set_permissions -p /pandora pandora ".*" ".*" ".*"

# Configure Pandora
install -o 108080 -g 108080 -m 750 -d ${PANDORA_CONF}
install -o 108080 -g 108080 -m 755 -d ${PANDORA_DATA}
install -o 108080 -g 108080 -m 640 pandora_conf/config.jsonc ${PANDORA_CONF}/config.jsonc
install -o 108080 -g 108080 -m 640 pandora_conf/gunicorn_config.py ${PANDORA_CONF}/gunicorn_config.py
envsubst <pandora_conf/local_settings.py | install -o 108080 -g 108080 -m 640 /dev/stdin ${PANDORA_CONF}/local_settings.py

# Populate database
spoc-container exec pandora -- /srv/pandora/pandora/manage.py migrate --noinput
spoc-container exec pandora -- /srv/pandora/pandora/manage.py sqlfindindex
spoc-container exec pandora -- /srv/pandora/pandora/manage.py sync_itemsort
spoc-container exec pandora -- /srv/pandora/pandora/manage.py sync_documentsort

# Create admin account
export PANDORA_ADMIN_USER="admin"
export PANDORA_ADMIN_EMAIL="admin@example.com"
export PANDORA_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d '+/=')
export PANDORA_ADMIN_HASH=$(spoc-container exec pandora -- sh -c "cd /srv/pandora && DJANGO_SETTINGS_MODULE=pandora.settings python3 -c \"from django.contrib.auth.hashers import make_password; print(make_password('${PANDORA_ADMIN_PWD}'))\"")
envsubst <adminpwd.sql | spoc-container exec pandora-postgres -- psql pandora

# Stop services required for setup
spoc-container stop pandora-postgres
spoc-container stop pandora-rabbitmq

# Register application
vmmgr register-app pandora pandora "${PANDORA_ADMIN_USER}" "${PANDORA_ADMIN_PWD}"
