#!/usr/bin/env bash
set -e
. /opt/elasticbeanstalk/support/envvars

cd $(cd $(dirname $0); echo $PWD)
test -x envvars.sh && . envvars.sh
test -x envvars_dev.sh && . envvars_dev.sh
cd ..
set -xe

EB_APP_USER=$(/opt/elasticbeanstalk/bin/get-config container -k app_user)

APP_CONFIG_URL=$(/opt/elasticbeanstalk/bin/get-config environment -k APP_CONFIG_URL)
if [ "" == "$APP_CONFIG_URL" ]; then
    echo "Missing environment variable. Please add 'APP_CONFIG_URL' to your environment configuration. Typical value may be something like 's3://my-amazon-s3-storage.tld/uws/playground/config'."
    exit 1
fi
export APP_CONFIG_URL;

rm -rf aws/config
aws s3 cp ${APP_CONFIG_URL} aws/config/ --recursive
chown -R ${EB_APP_USER}:${EB_APP_USER} aws

if [ -f aws/config/prod/parameters.yml ]; then
    echo "Found configuration for production environment at aws/config/prod."
elif [ -f aws/config/dev/parameters.yml ]; then
    echo "Found configuration for development environment at aws/config/dev."
else
    echo "Missing configuration file at aws/config/[prod|dev]/parameters.yml! Please check your configuration source ${APP_CONFIG_URL}"
    exit 1
fi
