#!/bin/sh
set -ev

# Volumes
MARIADB_CONF="${VOLUMES_DIR}/ushahidi/mariadb_conf"
MARIADB_DATA="${VOLUMES_DIR}/ushahidi/mariadb_data"
REDIS_CONF="${VOLUMES_DIR}/ushahidi/redis_conf"
REDIS_DATA="${VOLUMES_DIR}/ushahidi/redis_data"
USHAHIDI_CONF="${VOLUMES_DIR}/ushahidi/ushahidi_conf"
USHAHIDI_DATA="${VOLUMES_DIR}/ushahidi/ushahidi_data"

# Create MariaDB instance
install -o 100000 -g 100000 -m 755 -d ${MARIADB_CONF}
install -o 103306 -g 103306 -m 750 -d ${MARIADB_DATA}
install -o 100000 -g 100000 -m 644 mariadb_conf/my.cnf ${MARIADB_CONF}/my.cnf
spoc-container exec ushahidi-mariadb -- mysql_install_db --user=mysql --datadir=/var/lib/mysql --auth-root-authentication-method=socket --skip-test-db

# Create database
export USHAHIDI_PWD=$(head -c 18 /dev/urandom | base64 | tr -d '+/=')
spoc-container start ushahidi-mariadb
envsubst <createdb.sql | spoc-container exec ushahidi-mariadb -- mysql

# Configure Redis
install -o 100000 -g 106379 -m 750 -d ${REDIS_CONF}
install -o 106379 -g 106379 -m 750 -d ${REDIS_DATA}
install -o 100000 -g 106379 -m 640 redis_conf/redis.conf ${REDIS_CONF}/redis.conf
spoc-container start ushahidi-redis

# Configure Ushahidi
export USHAHIDI_APPKEY=$(head -c 32 /dev/urandom | base64 | tr -d '+/=' | cut -c0-32) # Must be exactly 32 characters
install -o 100000 -g 108080 -m 750 -d ${USHAHIDI_CONF}
install -o 108080 -g 108080 -m 755 -d ${USHAHIDI_DATA}
install -o 108080 -g 108080 -m 755 -d ${USHAHIDI_DATA}/passport
envsubst <ushahidi_conf/env | install -o 100000 -g 108080 -m 640 /dev/stdin ${USHAHIDI_CONF}/env
install -o 100000 -g 108080 -m 644 ushahidi_conf/config.json ${USHAHIDI_CONF}/config.json
spoc-container exec ushahidi -- sh -c 'cd /srv/ushahidi/platform; php artisan passport:keys'

# Populate database
spoc-container exec ushahidi -- sh -c 'cd /srv/ushahidi/platform; php artisan migrate'

# Create admin account
export USHAHIDI_ADMIN_USER="admin@example.com"
export USHAHIDI_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d '+/=')
export USHAHIDI_ADMIN_HASH=$(python3 -c "import bcrypt; print(bcrypt.hashpw('${USHAHIDI_ADMIN_PWD}'.encode(), bcrypt.gensalt()).decode().replace('2b', '2y'))")
envsubst <adminpwd.sql | spoc-container exec ushahidi-mariadb -- mysql ushahidi

# Stop services required for setup
spoc-container stop ushahidi-redis
spoc-container stop ushahidi-mariadb

# Register application
vmmgr register-app ushahidi ush "${USHAHIDI_ADMIN_USER}" "${USHAHIDI_ADMIN_PWD}"
