#!/bin/sh
set -ev

# Volumes
POSTGRES_DATA="${VOLUMES_DIR}/sigmah/postgres_data"
SIGMAH_DATA="${VOLUMES_DIR}/sigmah/sigmah_data"
SIGMAH_CONF="${VOLUMES_DIR}/sigmah/sigmah_conf"
SIGMAH_LAYER="${LAYERS_DIR}/sigmah_2.0.2-200403"

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

# Configure Sigmah
install -o 108080 -g 108080 -m 750 -d ${SIGMAH_CONF}
install -o 108080 -g 108080 -m 750 -d ${SIGMAH_DATA}
install -o 108080 -g 108080 -m 750 -d ${SIGMAH_DATA}/files
install -o 108080 -g 108080 -m 750 -d ${SIGMAH_DATA}/archives
envsubst <sigmah_conf/persistence.xml | install -o 108080 -g 108080 -m 640 /dev/stdin ${SIGMAH_CONF}/persistence.xml
install -o 108080 -g 108080 -m 640 sigmah_conf/sigmah.properties ${SIGMAH_CONF}/sigmah.properties
cp -p ${SIGMAH_LAYER}/srv/tomcat/webapps/sigmah/sigmah/images/header/org-default-logo.png ${SIGMAH_DATA}/files/logo.png

# Populate database
export SIGMAH_ADMIN_USER="Admin"
export SIGMAH_ADMIN_EMAIL="admin@example.com"
export SIGMAH_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d '+/=')
export SIGMAH_ADMIN_HASH=$(python3 -c "import bcrypt; print(bcrypt.hashpw('${SIGMAH_ADMIN_PWD}'.encode(), bcrypt.gensalt(prefix=b'2a')).decode())")
cat ${SIGMAH_LAYER}/srv/sigmah-MinimumDataKit.sql | spoc-container exec sigmah-postgres -- sh -c "PGPASSWORD=${SIGMAH_PWD} psql -U sigmah sigmah"
sed -e "s|§OrganizationName§|Demo organization|g" \
    -e "s|§OrganizationLogoFilename§|logo.png|g" \
    -e "s|§HeadquartersCountryCode§|CZ|g" \
    -e "s|§UserEmail§|${SIGMAH_ADMIN_EMAIL}|g" \
    -e "s|§UserName§|${SIGMAH_ADMIN_USER}|g" \
    -e "s|§UserFirstName§|${SIGMAH_ADMIN_USER}|g" \
    -e "s|§UserLocale§|en|g" \
    -e "s|\$2a\$10\$pMcTA1p9fefR8U9NoOPei.H0eq/TbbdSF27M0tn9iDWBrA4JHeCDC|${SIGMAH_ADMIN_HASH}|" \
    ${SIGMAH_LAYER}/srv/sigmah-newOrganizationLaunchScript.sql | spoc-container exec sigmah-postgres -- sh -c "PGPASSWORD=${SIGMAH_PWD} psql -U sigmah sigmah"

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

# Register application
vmmgr register-app sigmah sigmah "${SIGMAH_ADMIN_EMAIL}" "${SIGMAH_ADMIN_PWD}"
