#!/bin/sh
set -ev

# Volumes
POSTGRES_DATA="${VOLUMES_DIR}/cts/postgres_data"
CTS_CONF="${VOLUMES_DIR}/cts/cts_conf"
CTS_LAYER="${LAYERS_DIR}/cts_0.8.0-210106"

# 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

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

# Copy existing config files into persistent storage
cp -rp ${CTS_LAYER}/srv/cts/cts/settings ${CTS_CONF}

# Configure CTS
export CTS_SECRET=$(head -c 26 /dev/urandom | base64 | tr -d '+/=')
envsubst <cts_conf/spotter.py | install -o 100000 -g 108080 -m 640 /dev/stdin ${CTS_CONF}/spotter.py
install -o 100000 -g 108080 -m 640 /dev/null ${CTS_CONF}/__init__.py

# Populate database
spoc-container exec cts -- manage.py migrate

# Create admin account
export CTS_ADMIN_EMAIL="admin@example.com"
export CTS_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d '+/=')
export CTS_ADMIN_HASH=$(spoc-container exec cts -- python -c "from django.contrib.auth.hashers import make_password; print make_password('${CTS_ADMIN_PWD}')")
export CTS_ADMIN_SECRET=$(head -c 12 /dev/urandom | sha256sum | cut -c0-12)
envsubst <adminpwd.sql | spoc-container exec cts-postgres -- psql cts

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

# Register application
vmmgr register-app cts cts "${CTS_ADMIN_EMAIL}" "${CTS_ADMIN_PWD}"
