#!/bin/bash

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

# Install dependencies for Sahana
apt-get -y --no-install-recommends install python-dateutil python-imaging python-lxml python-matplotlib python-openid python-psycopg2 python-pyth python-reportlab python-requests python-shapely python-tweepy python-xlrd python-xlwt

# Install web2py
git clone --recursive https://github.com/web2py/web2py.git /srv/sambro
git -C /srv/sambro checkout cda35fd
git -C /srv/sambro submodule update

# Install Sahana
git clone --depth 1 https://github.com/sahana/eden.git /srv/sambro/applications/eden

# Install TwitterSearch 0.78.6
git clone --depth 1 https://github.com/ckoepp/TwitterSearch.git /tmp/TwitterSearch
cd /tmp/TwitterSearch
python setup.py install
cd -
rm -rf /tmp/TwitterSearch

# Copy Czech language file
cp ${SOURCE_DIR}/srv/sambro/applications/eden/languages/cs.py /srv/sambro/applications/eden/languages/cs.py

# Symlink fonts with Czech glyphs
ln -s /usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf /srv/sambro/applications/eden/static/fonts/DejaVuSerif-Bold.ttf
ln -s /usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf /srv/sambro/applications/eden/static/fonts/DejaVuSerif.ttf

# Create PostgreSQL user and database
export SAMBRO_PWD=$(head -c 18 /dev/urandom | base64)
envsubst <${SOURCE_DIR}/tmp/sambro-createdb.sql >/tmp/sambro-createdb.sql
sudo -u postgres psql -f /tmp/sambro-createdb.sql
rm -f /tmp/sambro-createdb.sql

# Configure web2py
rm -rf /srv/sambro/applications/{admin,examples,welcome}
cp ${SOURCE_DIR}/srv/sambro/routes.py /srv/sambro/routes.py
cp ${SOURCE_DIR}/srv/sambro/run_scheduler.py /srv/sambro/run_scheduler.py
ln -s /srv/sambro/handlers/wsgihandler.py /srv/sambro/wsgihandler.py

# Configure Sahana
mkdir /srv/sambro/applications/eden/{databases,errors,sessions}
mkdir -p /srv/sambro/applications/eden/static/cache/chart
mkdir -p /srv/sambro/applications/eden/uploads/{gis_cache,images,tracks}
export SAMBRO_HMAC=$(head -c 18 /dev/urandom | base64)
envsubst <${SOURCE_DIR}/srv/sambro/applications/eden/models/000_config.py >/srv/sambro/applications/eden/models/000_config.py
cp ${SOURCE_DIR}/srv/sambro/applications/eden/models/00_settings.py /srv/sambro/applications/eden/models/00_settings.py
export SAMBRO_ADMIN_USER=admin@example.com
export SAMBRO_ADMIN_PWD=$(head -c 12 /dev/urandom | base64)
cp ${SOURCE_DIR}/srv/sambro/applications/eden/modules/templates/SAMBRO/config.py /srv/sambro/applications/eden/modules/templates/SAMBRO/config.py
envsubst <${SOURCE_DIR}/srv/sambro/applications/eden/modules/templates/default/users/masterUsers.csv >/srv/sambro/applications/eden/modules/templates/default/users/masterUsers.csv

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

# Populate database
cd /srv/sambro
sudo -u sambro python web2py.py -S eden -M -R applications/eden/static/scripts/tools/noop.py

# Set "production values" (increases performance) only if the DEBUG environment variable is not set
if [ ${DEBUG:-0} -eq 0 ]; then
    sed -i 's/settings.base.migrate = True/settings.base.migrate = False/' /srv/sambro/applications/eden/models/000_config.py
    sed -i 's/settings.base.debug = True/settings.base.debug = False/' /srv/sambro/applications/eden/models/000_config.py
    sed -i 's/#settings.base.prepopulate = 0/settings.base.prepopulate = 0/' /srv/sambro/applications/eden/models/000_config.py
    sudo -u sambro python web2py.py -S eden -M -R applications/eden/static/scripts/tools/compile.py
fi

# Create uwsgi and nginx app definition
cp ${SOURCE_DIR}/etc/uwsgi/apps-available/sambro.ini /etc/uwsgi/apps-available/sambro.ini
ln -s /etc/uwsgi/apps-available/sambro.ini /etc/uwsgi/apps-enabled/sambro.ini
cp ${SOURCE_DIR}/etc/nginx/sites-available/sambro /etc/nginx/sites-available/sambro
ln -s /etc/nginx/sites-available/sambro /etc/nginx/sites-enabled/sambro

# Restart services
systemctl restart uwsgi
systemctl restart nginx

# Add portal application definition
portal-app-manager sambro "https://{host}:8099/eden/" "${SAMBRO_ADMIN_USER}" "${SAMBRO_ADMIN_PWD}"
portal-app-manager sambro-mobile

# TODO: Does matplotlib still require MPLCONFIGDIR directory?
# If so, /srv/sambro/wsgihandler.py needs to be modified

# TODO: Potentially needed dependencies
# WARNING:  Setup unresolved dependency: boto required for Setup Module
# WARNING:  S3Doc unresolved dependency: sunburnt required for Full-Text Search support
# WARNING:  S3GIS unresolved dependency: selenium required for Map printing support
# WARNING:  Setup unresolved dependency: PyYAML required for Setup Module
# WARNING:  S3GIS unresolved dependency: GDAL required for Shapefile support
# WARNING:  Setup unresolved dependency: ansible required for Setup Module
# WARNING:  Survey unresolved dependency: PyRTF required if you want to export assessment/survey templates as a Word document
# WARNING: Unresolved optional dependency: pyserial required
# WARNING:  Message Parsing unresolved dependency: TwitterSearch required for fetching results from twitter keyword queries

# TODO: Development notes
# vi /srv/sambro/applications/eden/modules/templates/default/config.py
# vi /srv/sambro/applications/eden/modules/s3cfg.py
# sudo -u sambro /srv/sambro/web2py.py -i 192.168.2.202 -a sambro --nogui
# sudo -u sambro openssl req -new -x509 -nodes -out /srv/sambro/cert.pem -keyout /srv/sambro/cert.key -subj "/C=CZ/CN=$(hostname -f)"
# sudo -u sambro /srv/sambro/web2py.py -i 192.168.2.202 -a sambro -c /srv/sambro/cert.pem -k /srv/sambro/cert.key --nogui
