#!/bin/sh

SOURCE_DIR=$(realpath $(dirname "${0}"))/seeddms

# Check prerequisites
docker image ls | grep -q postfix || $(realpath $(dirname "${0}"))/postfix.sh
docker image ls | grep -q postgres || $(realpath $(dirname "${0}"))/postgres.sh

# Build Docker container
docker build -t seeddms ${SOURCE_DIR}

# Populate database
export SEEDDMS_PWD=$(head -c 18 /dev/urandom | base64)
envsubst <${SOURCE_DIR}/createdb.sql | docker exec -i postgres psql
docker run --rm seeddms cat /srv/seeddms/create_tables-postgres.sql | docker exec -i -e PGPASSWORD=${SEEDDMS_PWD} postgres psql seeddms seeddms

# Copy existing files into persistent storage
mkdir -p /srv/seeddms/conf /srv/seeddms/data
docker run --rm -v /srv/seeddms/conf:/mnt/conf seeddms cp -rp /srv/seeddms/www/conf/. /mnt/conf
docker run --rm -v /srv/seeddms/data:/mnt/conf seeddms cp -rp /srv/seeddms/data/. /mnt/conf
chown -R 8010:8010 /srv/seeddms/data

# Configure SeedDMS
envsubst <${SOURCE_DIR}/srv/seeddms/conf/settings.xml >/srv/seeddms/conf/settings.xml
export SEEDDMS_ADMIN_USER=admin
export SEEDDMS_ADMIN_PWD=$(head -c 12 /dev/urandom | base64)
export SEEDDMS_ADMIN_EMAIL=admin@example.com
envsubst <${SOURCE_DIR}/adminpwd.sql | docker exec -i postgres psql seeddms
chown -R 8010:8010 /srv/seeddms/conf

# Create SeedDMS service
cp ${SOURCE_DIR}/etc/init.d/seeddms /etc/init.d/seeddms
rc-update add seeddms
service seeddms start

# Create nginx app definition
cp ${SOURCE_DIR}/etc/nginx/conf.d/seeddms.conf /etc/nginx/conf.d/seeddms.conf
service nginx reload

# Install cron job
cp ${SOURCE_DIR}/etc/periodic/hourly/seeddms /etc/periodic/hourly/seeddms

# Add portal application definition
portal-app-manager seeddms "https://{host}:8410/" "${SEEDDMS_ADMIN_USER}" "${SEEDDMS_ADMIN_PWD}"
