#!/bin/sh
set -e

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

# Check prerequisites
lxc-ls | grep -q postgres || $(realpath $(dirname "${0}"))/postgres.sh
service postgres start

# Build Docker container
docker build -t opendatakit-build ${SOURCE_DIR}
cp ${SOURCE_DIR}/etc/init.d/opendatakit-build /etc/init.d/opendatakit-build
rc-update -u

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

# Configure OpenDataKit Build
export OPENDATAKITBUILD_COOKIE_SECRET=$(head -c 8 /dev/urandom | hexdump -e '"%x"')
mkdir -p /srv/opendatakit-build/conf
envsubst <${SOURCE_DIR}/srv/opendatakit-build/conf/config.yml >/srv/opendatakit-build/conf/config.yml
docker run --rm -h opendatakit-build --link postgres -v /srv/opendatakit-build/conf/config.yml:/srv/opendatakit-build/config.yml -w /srv/opendatakit-build opendatakit-build rake db:migrate

# Stop services required for build
service postgres stop
