#!/bin/sh

SOURCE_DIR=${SOURCE_DIR}/ckan

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

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

# Configure CKAN Solr core
docker exec solr solr create -p 8983 -c ckan
cp ${SOURCE_DIR}/srv/solr/data/ckan/conf/schema.xml /srv/solr/data/ckan/conf/schema.xml
cp ${SOURCE_DIR}/srv/solr/data/ckan/conf/solrconfig.xml /srv/solr/data/ckan/conf/solrconfig.xml
chown 8983:8983 /srv/solr/data/ckan/conf/schema.xml
service solr restart

# Configure CKAN
export CKAN_SECRET=$(head -c 18 /dev/urandom | base64)
export CKAN_UUID=$(cat /proc/sys/kernel/random/uuid)
mkdir -p /srv/ckan/conf
mkdir /srv/ckan/data
envsubst <${SOURCE_DIR}/srv/ckan/conf/ckan.ini >/srv/ckan/conf/ckan.ini
cp ${SOURCE_DIR}/srv/ckan/conf/who.ini /srv/ckan/conf/who.ini
chown -R 8003:8003 /srv/ckan/data
cp ${SOURCE_DIR}/srv/ckan/update-ip.sh /srv/ckan/update-ip.sh
/srv/ckan/update-ip.sh

# Populate database
docker run --rm --link=postgres --link=redis --link=solr -v /srv/ckan/conf:/etc/ckan -v /srv/ckan/data:/srv/ckan/storage ckan paster --plugin=ckan db init -c /etc/ckan/ckan.ini
docker run --rm --link=postgres --link=redis --link=solr -v /srv/ckan/conf:/etc/ckan -v /srv/ckan/data:/srv/ckan/storage ckan paster --plugin=ckanext-spatial spatial initdb -c /etc/ckan/ckan.ini
docker run --rm --link=postgres --link=redis --link=solr -v /srv/ckan/conf:/etc/ckan -v /srv/ckan/data:/srv/ckan/storage ckan paster --plugin=ckan datastore set-permissions -c /etc/ckan/ckan.ini | docker exec -i postgres psql

# Create admin account
export CKAN_ADMIN_USER="admin"
export CKAN_ADMIN_UUID=$(cat /proc/sys/kernel/random/uuid)
export CKAN_ADMIN_APIKEY=$(cat /proc/sys/kernel/random/uuid)
export CKAN_ADMIN_PWD=$(head -c 12 /dev/urandom | base64)
export CKAN_ADMIN_HASH=$(docker run --rm ckan python -c "from passlib.hash import pbkdf2_sha512;print pbkdf2_sha512.encrypt('${CKAN_ADMIN_PWD}')")
export CKAN_ADMIN_EMAIL="admin@example.com"
envsubst <${SOURCE_DIR}/adminpwd.sql | docker exec -i postgres psql ckan

# Configure CKAN service
cp ${SOURCE_DIR}/etc/init.d/ckan /etc/init.d/ckan
rc-update add ckan boot
service ckan start

# Create nginx app definition
cp ${SOURCE_DIR}/etc/nginx/apps/ckan /etc/nginx/apps/ckan
cp ${SOURCE_DIR}/etc/nginx/conf.d/ckan.conf /etc/nginx/conf.d/ckan.conf

# Reload nginx configuration
service nginx reload

# Install cron job
cp ${SOURCE_DIR}/etc/periodic/hourly/ckan /etc/periodic/hourly/ckan

# Add portal application definition
portal-app-manager ckan "https://{host}:8403/" "${CKAN_ADMIN_USER}" "${CKAN_ADMIN_PWD}"
