#!/bin/sh
set -ev

# Volumes
POSTGRES_DATA="${VOLUMES_DIR}/ecogis/postgres_data"
ECOGIS_CONF="${VOLUMES_DIR}/ecogis/ecogis_conf"
ECOGIS_DATA="${VOLUMES_DIR}/ecogis/ecogis_data"

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

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

# Configure EcoGIS
install -o 108080 -g 108080 -m 750 ${ECOGIS_CONF}
install -o 108080 -g 108080 -m 750 ${ECOGIS_DATA}
envsubst <ecogis_conf/config.php | install -o 108080 -g 108080 -m 640 /dev/stdin ${ECOGIS_CONF}/config.php

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

# Register application
vmmgr register-app ecogis ecogis
