#!/bin/bash
# We write out configs with given environment variables and then run mekansm

SCRIPT_PATH=`dirname $0`
INSTALL_PATH=`dirname "${SCRIPT_PATH}"`


# Download credentials and config from S3
AWS_METADATA_HOST="169.254.169.254"
AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION:-us-west-2}
AWS_DEFAULT_REGION=$(curl -s http://${AWS_METADATA_HOST}/latest/dynamic/instance-identity/document | grep region | awk -F\" '{print $4}')
INSTANCE_ID=$(ec2metadata --instance-id)
EC2_TAG_NAME=$(AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION} aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=Name" --output=text | cut -f5)
EC2_TAG_OWNER=$(AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION} aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=Owner" --output=text | cut -f5)
TAG_OWNER=${EC2_TAG_OWNER:-dta}
TAG_NAME=${EC2_TAG_NAME:-mekansm-staging}

if [[ $EC2_TAG_NAME == "mekansm-"* ]]
then
    ENVIRONMENT=$(echo $EC2_TAG_NAME | cut -c 9-)
else
    ENVIRONMENT=$EC2_TAG_NAME
fi


AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION} /opt/twitch/mekansm/current/scripts/kms-decrypt.sh -a "${TAG_OWNER}-${TAG_NAME}" -d ~/.aws
. ~/.aws/environment.sh

# Setup variable defaults
USE_VIRTUAL_ENV=${USE_VIRTUAL_ENV:-true}
PYTHON_PATH=${PYTHON_PATH:-/usr}
PORT=${PORT:-8080}
AWS_PROFILE=${AWS_PROFILE:-twitch-core-services}
POSTGRES_USER=${POSTGRES_USER:-mekansm}
POSTGRES_DATABASE=${POSTGRES_DATABASE:-mekansm}
POSTGRES_PORT=${POSTGRES_PORT:-5432}
POSTGRES_HOST=${POSTGRES_HOST:-127.0.0.1}
POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-}
PYTHON_THREADPOOL_FREQUENCY=${PYTHON_THREADPOOL_FREQUENCY:-2}
PYTHON_THREADPOOL_MAX=${PYTHON_THREADPOOL_MAX:-40}

# sample yaml_config
cat << YML_CFG_EOF > ~/tmp/yaml_config
aws:
    -
        profile: ${AWS_PROFILE}
        region: ${AWS_DEFAULT_REGION}
database:
    host: ${POSTGRES_HOST}
    port: ${POSTGRES_PORT}
    user: ${POSTGRES_USER}
    password: ${POSTGRES_PASSWORD}
    database: ${POSTGRES_DATABASE}
    engine:
        echo: true
        echo_pool: true
        strategy: threadlocal
        max_overflow: 40
threadpool:
    frequency: ${PYTHON_THREADPOOL_FREQUENCY}
    max: ${PYTHON_THREADPOOL_MAX}
    maxspare: 40
    min: 20
    minspare: 10
    shrink_frequency: 10
    log_frequency: 3
YML_CFG_EOF

# Setup python and virtualenv
virtualenv --no-site-packages ~/venv
source ~/venv/bin/activate
easy_install -U pip
cd $INSTALL_PATH
pip install /opt/twitch/mekansm/current/
# exec is used since supervise does not manage subprocesses
exec python -m mekansm ${PORT} ~/tmp/yaml_config # Fire up the app
deactivate
