#!/bin/sh
set -ev

# Volumes
POSTGRES_DATA="${VOLUMES_DIR}/crisiscleanup/postgres_data"
CC_CONF="${VOLUMES_DIR}/crisiscleanup/cc_conf"
CC_LAYER="${LAYERS_DIR}/crisiscleanup_2.2.0-210106"

# Create Postgres instance
install -o 105432 -g 105432 -m 700 -d ${POSTGRES_DATA}
spoc-container exec crisiscleanup-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 database
export CRISISCLEANUP_PWD=$(head -c 18 /dev/urandom | base64 | tr -d '+/=')
spoc-container start crisiscleanup-postgres
envsubst <createdb.sql | spoc-container exec crisiscleanup-postgres -- psql

# Copy existing config files into persistent storage
cp -rp ${CC_LAYER}/srv/crisiscleanup/config ${CC_CONF}

# Configure CrisisCleanup
export CRISISCLEANUP_ADMIN_USER="Admin"
export CRISISCLEANUP_ADMIN_EMAIL="admin@example.com"
export CRISISCLEANUP_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d '+/=')
export CRISISCLEANUP_SECRET=$(spoc-container exec crisiscleanup -- rake secret)
envsubst <cc_conf/database.yml | install -o 108080 -g 108080 -m 600 /dev/stdin ${CC_CONF}/database.yml
envsubst <cc_conf/secrets.yml | install -o 108080 -g 108080 -m 600 /dev/stdin ${CC_CONF}/secrets.yml
install -o 108080 -g 108080 -m 640 cc_conf/boot.rb ${CC_CONF}/boot.rb
install -o 108080 -g 108080 -m 640 cc_conf/initializers/devise.rb ${CC_CONF}/initializers/devise.rb
install -o 108080 -g 108080 -m 640 cc_conf/environments/production.rb ${CC_CONF}/environments/production.rb

# Populate database
spoc-container exec crisiscleanup -- rake db:schema:load
envsubst <adminpwd.rb | spoc-container exec crisiscleanup -- sh -c 'cd /srv/crisiscleanup; bin/rails console -e production'

# Stop services required for setup
spoc-container stop crisiscleanup-postgres

# Register application
vmmgr register-app crisiscleanup cc "${CRISISCLEANUP_ADMIN_EMAIL}" "${CRISISCLEANUP_ADMIN_PWD}"
