#!/bin/sh

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

# 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 odk ${SOURCE_DIR}

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

# Configure OpenDataKit
export ODK_ADMIN_USER=admin
export ODK_ADMIN_REALM=spotter
mkdir -p /srv/odk/conf
envsubst <${SOURCE_DIR}/srv/odk/conf/jdbc.properties >/srv/odk/conf/jdbc.properties
envsubst <${SOURCE_DIR}/srv/odk/conf/security.properties >/srv/odk/conf/security.properties
cp ${SOURCE_DIR}/srv/odk/conf/server.xml /srv/odk/conf/server.xml
cp ${SOURCE_DIR}/srv/odk/update-url.sh /srv/odk/update-url.sh
chown -R 8015:8015 /srv/odk/conf

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

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

# Add application definition
spotter-appmgr add-app odk "https://odk.{host}/aggregate/" "${ODK_ADMIN_USER}" "${ODK_ADMIN_PWD}"
spotter-appmgr add-app odk-clients -p clienturl "https://odk.{host}/aggregate"
