echo -e "\nLogging into Amazon ECR..."
aws ecr get-login-password --region {{ environment.collection.region }} | \
docker login -u AWS --password-stdin {{ service.image_registry_url().split('/')[0] }}

{{ render_template("Dockerfile.j2", "Dockerfile") }}
# copy config from default location
AWS_DEFAULT_CONFIG_DIR=~/.aws
if test -d "$AWS_DEFAULT_CONFIG_DIR"
then
    cp -r ~/.aws {{ toolbox.rendered_files_path }}/.aws
else
    mkdir {{ toolbox.rendered_files_path }}/.aws
fi

# copy config file if exists
CONFIG_FILE_PATH=${AWS_CONFIG_FILE:-~/.aws/config}
if test -e "$CONFIG_FILE_PATH"
then
    cp $CONFIG_FILE_PATH {{ toolbox.rendered_files_path }}/.aws/config
fi

# copy creds file if exists
CREDS_FILE_PATH=${AWS_SHARED_CREDENTIALS_FILE:-~/.aws/credentials}
if test -e "$CREDS_FILE_PATH"
then
    cp $CREDS_FILE_PATH {{ toolbox.rendered_files_path }}/.aws/credentials
fi

docker pull {{ service.image_for_tag(toolbox.tag_for_service(service.name)) }}

docker build -t {{ service.instance_name }}_toolbox \
--build-arg AWS_REGION=$AWS_REGION \
--build-arg AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION \
--build-arg AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \
--build-arg AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \
--build-arg AWS_SESSION_TOKEN=$AWS_SESSION_TOKEN \
-f {{ toolbox.rendered_files_path }}/Dockerfile {{ toolbox.rendered_files_path }}

{%- if command %}
{# Allow time for port forwarding processes to start #}
sleep ${CNC_TOOLBOX_CMD_DELAY_SECONDS:-15}
{%- endif %}

USER=$(docker inspect --format='{{"{{.Config.User}}"}}' {{ service.instance_name }}_toolbox)
if [ -z "$USER" ]; then
    USER="root"
fi

# Start & exec into docker container
docker run --user $USER --entrypoint sh \
{%- for variable in toolbox.environment_items -%}
-e {{ variable.name }}={{ shlex.quote(variable.value) }} \
{%- endfor -%}
--network ${CNC_TOOLBOX_NETWORK:-host} \
{%- if command %}
--rm --name app {{ service.instance_name }}_toolbox -c '{{ command }}'; command_result=$?
{%- else %}
-it --rm --name app {{ service.instance_name }}_toolbox
{%- endif %}

{%- if command %}
exit $command_result
{%- endif %}
