#!/bin/sh
set -ev

# Volumes
POSTGRES_DATA="${VOLUMES_DIR}/opendatakit/postgres_data"
ODK_CONF="${VOLUMES_DIR}/opendatakit/odk_conf"
ODKBUILD_CONF="${VOLUMES_DIR}/opendatakit/odkbuild_conf"

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

# Configure OpenDataKit
export OPENDATAKIT_ADMIN_USER="admin"
export OPENDATAKIT_ADMIN_REALM="spotter"
install -o 108080 -g 108080 -m 750 -d ${ODK_CONF}
envsubst <odk_conf/jdbc.properties | install -o 108080 -g 108080 -m 640 /dev/stdin ${ODK_CONF}/jdbc.properties
envsubst <odk_conf/security.properties | install -o 108080 -g 108080 -m 640 /dev/stdin ${ODK_CONF}/security.properties
install -o 108080 -g 108080 -m 640 odk_conf/server.xml ${ODK_CONF}/server.xml

# Configure OpenDataKit Build
export OPENDATAKITBUILD_COOKIE_SECRET=$(head -c 8 /dev/urandom | hexdump -e '"%x"')
install -o 108080 -g 108080 -m 750 -d ${ODKBUILD_CONF}
install -o 108080 -g 108080 -m 640 odkbuild_conf/add-ca-cert.env ${ODKBUILD_CONF}/add-ca-cert.env
envsubst <odkbuild_conf/config.yml | install -o 108080 -g 108080 -m 640 /dev/stdin ${ODKBUILD_CONF}/config.yml
spoc-container exec opendatakit-build -- sh -c 'cd /srv/opendatakit-build; rake db:migrate'

# Populate database
spoc-container start opendatakit
until grep -q 'org.apache.catalina.startup.Catalina.start Server startup' /var/log/spoc/opendatakit.log; do
    sleep 1
done
spoc-container stop opendatakit

# Update admin account
export OPENDATAKIT_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d '+/=')
export OPENDATAKIT_ADMIN_SALT=$(head -c 4 /dev/urandom | hexdump -e '"%x"') # Must be exactly 8 characters
export OPENDATAKIT_ADMIN_BASIC_HASH=$(echo -n "${OPENDATAKIT_ADMIN_PWD}{${OPENDATAKIT_ADMIN_SALT}}" | sha1sum | tr -d " -")
export OPENDATAKIT_ADMIN_DIGEST_HASH=$(echo -n "${OPENDATAKIT_ADMIN_USER}:${OPENDATAKIT_ADMIN_REALM}:${OPENDATAKIT_ADMIN_PWD}" | md5sum | tr -d " -")
envsubst <adminpwd.sql | spoc-container exec opendatakit-postgres -- psql opendatakit

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

# Register application
vmmgr register-app opendatakit odk "${OPENDATAKIT_ADMIN_USER}" "${OPENDATAKIT_ADMIN_PWD}"
vmmgr register-app opendatakit-build odkbuild
