#!/bin/sh

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

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

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

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

# Copy existing config files into persistent storage
mkdir -p /srv/ccleanup/conf
chown 8005:8005 /srv/ccleanup/conf
docker run --rm -v /srv/ccleanup/conf:/mnt/conf ccleanup cp -rp /srv/ccleanup/config/. /mnt/conf
chown root:root /srv/ccleanup/conf

# Configure CrisisCleanup
export CCLEANUP_ADMIN_USER="Admin"
export CCLEANUP_ADMIN_EMAIL="admin@example.com"
export CCLEANUP_ADMIN_PWD=$(head -c 12 /dev/urandom | base64)
envsubst <${SOURCE_DIR}/srv/ccleanup/conf/database.yml >/srv/ccleanup/conf/database.yml
cp ${SOURCE_DIR}/srv/ccleanup/conf/boot.rb /srv/ccleanup/conf/boot.rb
cp ${SOURCE_DIR}/srv/ccleanup/conf/initializers/devise.rb /srv/ccleanup/conf/initializers/devise.rb
cp ${SOURCE_DIR}/srv/ccleanup/conf/environments/production.rb /srv/ccleanup/conf/environments/production.rb

# Populate database
envsubst <${SOURCE_DIR}/srv/ccleanup/db/seeds.rb >/tmp/seeds.rb
docker run --rm -h ccleanup --link postgres -v /srv/ccleanup/conf:/srv/ccleanup/config ccleanup rake db:schema:load
docker run --rm -h ccleanup --link postgres -v /srv/ccleanup/conf:/srv/ccleanup/config -v /tmp/seeds.rb:/srv/ccleanup/db/seeds.rb ccleanup rake db:seed
rm /tmp/seeds.rb

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

# Add application definition
spotter-appmgr add-app ccleanup "https://ccleanup.{host}/" "${CCLEANUP_ADMIN_EMAIL}" "${CCLEANUP_ADMIN_PWD}"
