#!/bin/bash

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

# Install dependencies for Ushahidi
apt-get -y --no-install-recommends install php7.0-curl php7.0-gd php7.0-fpm php7.0-json php7.0-imap php7.0-mcrypt php7.0-mysql

# Install Ushahidi
wget https://github.com/ushahidi/platform-release/releases/download/v3.7.1/ushahidi-platform-release-v3.7.1.tar.gz -O /tmp/ushahidi.tar.gz
tar xzf /tmp/ushahidi.tar.gz -C /tmp
mv /tmp/ushahidi-platform-release-v3.7.1/html /srv/ushahidi
rm -f /tmp/ushahidi.tar.gz
rm -rf /tmp/ushahidi-platform-release-v3.7.1

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

# Configure Ushahidi
envsubst <${SOURCE_DIR}/srv/ushahidi/platform/.env >/srv/ushahidi/platform/.env

# Populate database
cd /srv/ushahidi/platform
./bin/phinx migrate -c application/phinx.php

# Create admin account
export USHAHIDI_ADMIN_USER=admin@example.com
export USHAHIDI_ADMIN_PWD=$(head -c 12 /dev/urandom | base64)
export USHAHIDI_ADMIN_HASH=$(php -r "echo password_hash('${USHAHIDI_ADMIN_PWD}', PASSWORD_BCRYPT);")
envsubst <${SOURCE_DIR}/tmp/ushahidi-adminpwd.sql >/tmp/ushahidi-adminpwd.sql
mysql ushahidi </tmp/ushahidi-adminpwd.sql
rm -f /tmp/ushahidi-adminpwd.sql

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

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

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

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

# Add portal application definition
portal-app-manager ushahidi "https://{host}:8002/" "${USHAHIDI_ADMIN_USER}" "${USHAHIDI_ADMIN_PWD}"
portal-app-manager ushahidi-mobile
