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

cd $(cd $(dirname $0); echo $PWD)
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/idp/playground/config'."
    exit 1
fi
export APP_CONFIG_URL;

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

set +e
ls aws_config/.env.* 2&>1 /dev/null
if [ 0 != $? ]; then
    echo "Missing file at ${$APP_CONFIG_URL}/.env.*! Please check your configuration."
    exit 1
fi
set -e

if [ ! -d aws_config/saml ]; then
    echo "Missing SAML configuration directory at ${$APP_CONFIG_URL}/saml! Please check your configuration."
    exit 1
fi

cp -a aws_config/.env.* .

mkdir -p config/saml/prod
cp -a aws_config/saml/* config/saml/prod/.

rm -rf aws_config
