#!/bin/sh

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

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

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

# Create databases
export OPENDATAKIT_PWD=$(head -c 18 /dev/urandom | base64)
envsubst <${SOURCE_DIR}/createdb.sql | docker exec -i postgres psql

# Configure OpenDataKit
export OPENDATAKIT_ADMIN_USER=admin
export OPENDATAKIT_ADMIN_REALM=spotter
mkdir -p /srv/opendatakit/conf /srv/opendatakit/data
envsubst <${SOURCE_DIR}/srv/opendatakit/conf/jdbc.properties >/srv/opendatakit/conf/jdbc.properties
envsubst <${SOURCE_DIR}/srv/opendatakit/conf/security.properties >/srv/opendatakit/conf/security.properties
cp ${SOURCE_DIR}/srv/opendatakit/conf/server.xml /srv/opendatakit/conf/server.xml
cp ${SOURCE_DIR}/srv/opendatakit/update-ip.sh /srv/opendatakit/update-ip.sh
chown -R 8015:8015 /srv/opendatakit/conf /srv/opendatakit/data

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

# Update admin account
export OPENDATAKIT_ADMIN_PWD=$(head -c 12 /dev/urandom | base64)
export OPENDATAKIT_ADMIN_SALT=$(head -c 4 /dev/urandom | hexdump -e '"%x"') # Must be 8 characters
export OPENDATAKIT_ADMIN_BASIC_HASH=$(echo -n "${OPENDATAKIT_ADMIN_PWD}{${OPENDATAKIT_ADMIN_SALT}}" | sha1sum | tr -d " -")
export OPENDATAKIT_ADMIN_DIGEST_HASH=$(echo -n "${OPENDATAKIT_ADMIN_USER}:${OPENDATAKIT_ADMIN_REALM}:${OPENDATAKIT_ADMIN_PWD}" | md5sum | tr -d " -")
until docker logs opendatakit 2>&1 | grep -q 'org.apache.catalina.startup.Catalina.start'; do
    sleep 1
done
envsubst <${SOURCE_DIR}/adminpwd.sql | docker exec -i postgres psql opendatakit

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

# Add portal application definition
portal-app-manager opendatakit "https://{host}:8415/aggregate/" "${OPENDATAKIT_ADMIN_USER}" "${OPENDATAKIT_ADMIN_PWD}"
portal-app-manager opendatakit-clients -p clienturl "http://{host}:8815/aggregate"
