#!/bin/sh
set -ev

# Volumes
POSTGRES_DATA="${VOLUMES_DIR}/motech/postgres_data"
ACTIVEMQ_CONF="${VOLUMES_DIR}/motech/activemq_conf"
ACTIVEMQ_DATA="${VOLUMES_DIR}/motech/activemq_data"
MOTECH_CONF="${VOLUMES_DIR}/motech/motech_conf"

# Create Postgres instance
install -o 105432 -g 105432 -m 700 -d ${POSTGRES_DATA}
spoc-container exec motech-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

# Configure ActiveMQ
install -o 161616 -g 161616 -m 750 -d ${ACTIVEMQ_CONF}
install -o 161616 -g 161616 -m 750 -d ${ACTIVEMQ_DATA}
install -o 161616 -g 161616 -m 640 activemq_conf/activemq.xml ${ACTIVEMQ_CONF}/activemq.xml

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

# Configure Motech
install -o 108080 -g 108080 -m 750 -d ${MOTECH_CONF}
install -o 108080 -g 108080 -m 750 -d ${MOTECH_CONF}/config
install -o 108080 -g 108080 -m 750 -d ${MOTECH_CONF}/config/org.motechproject.motech-platform-email
envsubst <motech_conf/config/bootstrap.properties | install -o 108080 -g 108080 -m 640 /dev/stdin ${MOTECH_CONF}/config/bootstrap.properties
install -o 108080 -g 108080 -m 640 motech_conf/config-locations.properties ${MOTECH_CONF}/config-locations.properties
install -o 108080 -g 108080 -m 640 motech_conf/config/motech-settings.properties ${MOTECH_CONF}/config/motech-settings.properties
install -o 108080 -g 108080 -m 640 motech_conf/config/org.motechproject.motech-platform-email/motech-email.properties ${MOTECH_CONF}/config/org.motechproject.motech-platform-email/motech-email.properties

# Populate database and create admin account
spoc-container start motech-activemq
spoc-container start motech
MOTECH_IP=$(grep ' motech$' /var/lib/spoc/hosts | cut -d' ' -f0)
until curl -s "http://${MOTECH_IP}:8080/module/server/startup/" | grep -q adminLogin; do
    sleep 1
done
export MOTECH_ADMIN_USER="admin"
export MOTECH_ADMIN_EMAIL="admin@example.com"
export MOTECH_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d '+/=')
curl -H "Content-Type: application/json" -X POST -d "{\"adminLogin\":\"${MOTECH_ADMIN_USER}\",\"adminEmail\":\"${MOTECH_ADMIN_EMAIL}\",\"adminPassword\":\"${MOTECH_ADMIN_PWD}\",\"adminConfirmPassword\":\"${MOTECH_ADMIN_PWD}\",\"language\":\"cs\",\"providerName\":\"\",\"providerUrl\":\"\",\"schedulerUrl\":\"\"}" "http://${MOTECH_IP}:8080/module/server/startup/"
spoc-container stop motech

# Stop services required for setup
spoc-container stop motech-activemq
spoc-container stop motech-postgres

# Register application
vmmgr register-app motech motech "${MOTECH_ADMIN_USER}" "${MOTECH_ADMIN_PWD}"
