#!/bin/bash

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

# Download Mifos X
mkdir -p /srv/mifosx/fineract-provider
wget https://sourceforge.net/projects/mifos/files/latest/download -O /tmp/mifosx.zip
unzip /tmp/mifosx.zip -d /tmp
unzip /tmp/fineractplatform-17.07.01.RELEASE/fineract-provider.war -d /srv/mifosx/fineract-provider
mv /tmp/fineractplatform-17.07.01.RELEASE/apps/community-app /srv/mifosx/community-app
rm -f /tmp/mifosx.zip

# Download Java library dependencies
wget http://central.maven.org/maven2/org/drizzle/jdbc/drizzle-jdbc/1.3/drizzle-jdbc-1.3.jar -O /var/lib/tomcat8/lib/drizzle-jdbc-1.3.jar

# Create databases
export MIFOSX_PWD=$(head -c 18 /dev/urandom | base64)
envsubst <${SOURCE_DIR}/tmp/mifosx-createdb.sql >/tmp/mifosx-createdb.sql
mysql </tmp/mifosx-createdb.sql
rm -f /tmp/mifosx-createdb.sql

# Populate database
mysql mifosplatform-tenants </tmp/fineractplatform-17.07.01.RELEASE/database/mifospltaform-tenants-first-time-install.sql
envsubst <${SOURCE_DIR}/tmp/mifosx-schemapwd.sql >/tmp/mifosx-schemapwd.sql
mysql mifosplatform-tenants </tmp/mifosx-schemapwd.sql
rm -f /tmp/mifosx-schemapwd.sql

# Update admin account
export MIFOSX_ADMIN_USER=admin
export MIFOSX_ADMIN_EMAIL=admin@example.com
export MIFOSX_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d "+")
export MIFOSX_ADMIN_HASH=$(echo -n "${MIFOSX_ADMIN_PWD}{1}" | sha256sum | awk '{print $1}')
envsubst <${SOURCE_DIR}/tmp/mifosx-adminpwd.sql >>/srv/mifosx/fineract-provider/WEB-INF/classes/sql/migrations/core_db/V3__mifosx-permissions-and-authorisation-utf8.sql

# Configure Mifos X
envsubst <${SOURCE_DIR}/srv/mifosx/fineract-provider/META-INF/context.xml >/srv/mifosx/fineract-provider/META-INF/context.xml
cp ${SOURCE_DIR}/srv/mifosx/fineract-provider/WEB-INF/classes/application.properties /srv/mifosx/fineract-provider/WEB-INF/classes/application.properties
sed -i 's/requires-channel="https" //g' /srv/mifosx/fineract-provider/WEB-INF/classes/META-INF/spring/securityContext.xml
chown -R tomcat8:tomcat8 /srv/mifosx/fineract-provider
ln -s /srv/mifosx/fineract-provider /var/lib/tomcat8/webapps/fineract-provider

# Create nginx site definition
cp ${SOURCE_DIR}/etc/nginx/apps-available/mifosx /etc/nginx/apps-available/mifosx
ln -s /etc/nginx/apps-available/mifosx /etc/nginx/apps-enabled/mifosx

# Restart services
systemctl restart tomcat8
systemctl restart nginx

# Cleanup
rm -rf /tmp/fineractplatform-17.07.01.RELEASE

# Add portal application definition
portal-app-manager mifosx "/mifosx/" "${MIFOSX_ADMIN_USER}" "${MIFOSX_ADMIN_PWD}"
portal-app-manager mifosx-mobile
