#!/bin/bash

set -e

. ${INSTALLER_DIR}/wizard

CLI="${APP_NAME}"

# Check for custom gems
custom_gemfile=$(${CLI} config:get CUSTOM_PLUGIN_GEMFILE || echo "")
if [ -e "${custom_gemfile}"]; then

	# Need to override the frozen setting for the vendored gems
	${CLI} run bundle config --local frozen 0

	# Re-bundle the application including gems
	${CLI} run bundle install

	# Mark assets for recompilation in the OpenProject postinstall rake step
	${CLI} config:set REBUILD_ASSETS="true"

fi

rake_commands="db:migrate db:seed"

# set rails_cache_store
memcached_servers="$(${CLI} config:get MEMCACHED_SERVERS || echo "")"
if [ -z "$memcached_servers" ]; then
	${CLI} config:set RAILS_CACHE_STORE=file_store
else
	${CLI} config:set RAILS_CACHE_STORE=memcache
fi

# create attachments folder
attachments_path=$(${CLI} config:get ATTACHMENTS_STORAGE_PATH || echo "/var/db/${APP_NAME}/files")
mkdir -p "${attachments_path}"
chown ${APP_USER}.${APP_GROUP} "${attachments_path}"
${CLI} config:set ATTACHMENTS_STORAGE_PATH="${attachments_path}"

# set web host
${CLI} config:set HOST=127.0.0.1

# set web concurrency
web_concurrency=$(${CLI} config:get WEB_CONCURRENCY || echo "2")
${CLI} config:set WEB_CONCURRENCY=${web_concurrency}

# set web timeout
web_timeout=$(${CLI} config:get WEB_TIMEOUT || echo "15")
${CLI} config:set WEB_TIMEOUT=${web_timeout}

# set SECRET_KEY_BASE env variable
secret_token=$(${CLI} config:get SECRET_KEY_BASE || ${CLI} config:get SECRET_TOKEN || ${CLI} run rake -s secret | tail -1)
${CLI} config:set SECRET_KEY_BASE="$secret_token"

# set SECRET_TOKEN env variable for backwards compatibility
${CLI} config:set SECRET_TOKEN="$secret_token"

# Allow other tasks to run before the environment is loaded
${CLI} run rake "packager:before_postinstall"

# Use the OpenProject internal setup in one environment task
${CLI} run rake "${rake_commands} packager:postinstall"

# Allow OpenProject to perform custom initialization steps in the context of this installer
if [ -e "${APP_HOME}/packaging/scripts/postinstall" ]; then
	source "${APP_HOME}/packaging/scripts/postinstall"
fi

# scale
${CLI} scale web=1 worker=1 || true

# restart
service ${APP_NAME} restart
