#!/bin/bash

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

# Install dependencies for SeedDMS
apt-get -y --no-install-recommends install ghostscript id3 imagemagick libreoffice-calc libreoffice-impress libreoffice-writer php7.0-gd php7.0-fpm php7.0-mbstring php7.0-pgsql php7.0-xml php-pear poppler-utils unoconv

# Install SeedDMS
wget https://sourceforge.net/projects/seeddms/files/seeddms-5.1.3/seeddms-quickstart-5.1.3.tar.gz/download -O /srv/seeddms.tgz
tar xzf /srv/seeddms.tgz -C /srv
mv /srv/seeddms51x /srv/seeddms
rm -f /srv/seeddms.tgz

# Patch Previewers
patch -d /srv/seeddms -p0 <${SOURCE_DIR}/seeddms-previewers.patch

# Populate database
export SEEDDMS_PWD=$(head -c 18 /dev/urandom | base64)
envsubst <${SOURCE_DIR}/tmp/seeddms-createdb.sql >/tmp/seeddms-createdb.sql
sudo -u postgres psql -f /tmp/seeddms-createdb.sql
rm -f /tmp/seeddms-createdb.sql
export PGPASSWORD=${SEEDDMS_PWD}
psql -f /srv/seeddms/www/install/create_tables-postgres.sql seeddms seeddms

# Configure SeedDMS
envsubst <${SOURCE_DIR}/srv/seeddms/www/conf/settings.xml >/srv/seeddms/www/conf/settings.xml
rm -rf /srv/seeddms/www/install/
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}/tmp/seeddms-adminpwd.sql >/tmp/seeddms-adminpwd.sql
psql -f /tmp/seeddms-adminpwd.sql seeddms seeddms
unset PGPASSWORD
rm -f /tmp/seeddms-adminpwd.sql

# Create OS user
adduser --system --group --home /srv/seeddms --shell /bin/false seeddms
chown -R seeddms:www-data /srv/seeddms/

# Create PHP and nginx app definition
cp ${SOURCE_DIR}/etc/php/7.0/fpm/pool.d/seeddms.conf /etc/php/7.0/fpm/pool.d/seeddms.conf
cp ${SOURCE_DIR}/etc/nginx/apps-available/seeddms /etc/nginx/apps-available/seeddms
ln -s /etc/nginx/apps-available/seeddms /etc/nginx/apps-enabled/seeddms

# Restart services
systemctl restart php7.0-fpm
systemctl restart nginx

# Install cron job
cp ${SOURCE_DIR}/etc/cron.d/seeddms /etc/cron.d/seeddms

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