#!/bin/sh
set -ev

# Volumes
POSTGRES_DATA="${VOLUMES_DIR}/kanboard/postgres_data"
KANBOARD_CONF="${VOLUMES_DIR}/kanboard/kanboard_conf"
KANBOARD_DATA="${VOLUMES_DIR}/kanboard/kanboard_data"

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

# Configure Kanboard
export KANBOARD_PWD=$(head -c 18 /dev/urandom | base64 | tr -d '+/=')
install -o 108080 -g 108080 -m 750 -d ${KANBOARD_CONF}
install -o 108080 -g 108080 -m 750 -d ${KANBOARD_DATA}
envsubst <kanboard_conf/config.php | install -o 108080 -g 108080 -m 640 /dev/stdin ${KANBOARD_CONF}/config.php

# Populate database
spoc-container start kanboard-postgres
envsubst <createdb.sql | spoc-container exec kanboard-postgres -- psql
spoc-container exec kanboard -- cat /srv/kanboard/app/Schema/Sql/postgres.sql | spoc-container exec kanboard-postgres -- sh -c "PGPASSWORD=${KANBOARD_PWD} psql kanboard kanboard"

# Create admin account
export KANBOARD_ADMIN_USER="admin"
export KANBOARD_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d '+/=')
export KANBOARD_ADMIN_HASH=$(python3 -c "import bcrypt; print(bcrypt.hashpw('${KANBOARD_ADMIN_PWD}'.encode(), bcrypt.gensalt()).decode().replace('2b', '2y'))")
envsubst <adminpwd.sql | spoc-container exec kanboard-postgres -- psql kanboard

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

# Register application
vmmgr register-app kanboard kb "${KANBOARD_ADMIN_USER}" "${KANBOARD_ADMIN_PWD}"
