#!/bin/bash

# rewrite snipr4 config file (TODO: does not seem to be effective)

# CONF_DESTINATION=$PHP_INI_DIR/conf.d/snipr4.ini
# rm $CONF_DESTINATION || echo "config file did not exist, that's okay"
# touch $CONF_DESTINATION
# echo "snipr4_db_host = $SNIPR_DB_HOST" >> $CONF_DESTINATION
# echo "snipr4_db_name = $SNIPR_DB_NAME" >> $CONF_DESTINATION
# echo "snipr4_db_username = $SNIPR_DB_USERNAME" >> $CONF_DESTINATION
# echo "snipr4_db_password = $SNIPR_DB_PASSWORD" >> $CONF_DESTINATION
# echo "this is invalid config" >> $CONF_DESTINATION

# echo ">> snipr4.ini:" # TODO: remove this, exposes secrets
# cat $CONF_DESTINATION

cat 000-default.conf | \
	sed s/__DB_HOST__/${DB_HOST}/ | \
	sed s/__DB_NAME__/${DB_NAME}/ | \
	sed s/__DB_USERNAME__/${DB_USERNAME}/ | \
	sed s/__DB_PASSWORD__/${DB_PASSWORD}/ \
	> /tmp/000-default.conf
mv /tmp/000-default.conf /etc/apache2/sites-available/000-default.conf

ENV_FILE=/opt/environment
echo "export ONESPACE_SERVICE_GUID=\"${ONESPACE_SERVICE_GUID}\"" >> $ENV_FILE
echo "export ONESPACE_SERVICE_AUTHKEY=\"${ONESPACE_SERVICE_AUTHKEY}\"" >> $ENV_FILE

# echo "export DB_HOST=\"${DB_HOST}\"" > $ENV_FILE
# echo "export DB_NAME=\"${DB_NAME}\"" >> $ENV_FILE
# echo "export DB_USERNAME=\"${DB_USERNAME}\"" >> $ENV_FILE
# echo "export DB_PASSWORD=\"${DB_PASSWORD}\"" >> $ENV_FILE
# echo "export SERVICE_URL_USER_API=\"${SERVICE_URL_USER_API}\"" >> $ENV_FILE
# echo "export SERVICE_URL_SERVICE_API=\"${SERVICE_URL_SERVICE_API}\"" >> $ENV_FILE
# echo "export SERVICE_URL_USER_UI=\"${SERVICE_URL_USER_UI}\"" >> $ENV_FILE
# echo "export IMAGE_SERVICE_BASE_PATH=\"${IMAGE_SERVICE_BASE_PATH}\"" >> $ENV_FILE

# set up the db
# disabled till a db is required
# /usr/local/bin/php /var/www/html/yii migrate/up --interactive=0

## Load Keys
source /opt/environment && cd /var/www/html/ && php yii cron/load-user-validation-keys >> /var/log/cron.log 2>&1
source /opt/environment && cd /var/www/html/ && php yii cron/load-service-validation-keys >> /var/log/cron.log 2>&1

# run
# apache creates a pid file that can prevent it from restarting after reboots - delete it before trying to launch
rm -f /run/apache2/apache2.pid
# apache2-foreground
/usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf
