{{ render_template("Dockerfile.j2", "Dockerfile") }}
# copy config from default location
if [ ! -d "{{ toolbox.rendered_files_path }}/.config" ]
then
    mkdir -p "{{ toolbox.rendered_files_path }}/.config"
fi

GCP_DEFAULT_CONFIG_DIR=${CLOUDSDK_CONFIG:-$HOME/.config/gcloud}
if [ -d "$GCP_DEFAULT_CONFIG_DIR" ]
then
    cp -R "$GCP_DEFAULT_CONFIG_DIR" "{{ toolbox.rendered_files_path }}/.config/gcloud"
else
    mkdir -p "{{ toolbox.rendered_files_path }}/.config/gcloud"
fi

# If google credentials file is set then we copy
# to known location and set correct GOOGLE_APPLICATION_CREDENTIALS path
# for the toolbox Dockerfile
if [ -n "$GOOGLE_APPLICATION_CREDENTIALS" ]
then
    if [ -e "$GOOGLE_APPLICATION_CREDENTIALS" ]
    then
        cp "$GOOGLE_APPLICATION_CREDENTIALS" "{{ toolbox.rendered_files_path }}/service_account.json"
        TOOLBOX_GOOGLE_APPLICATION_CREDENTIALS="/_cnc_temp/service_account.json"
    fi
fi
touch "{{ toolbox.rendered_files_path }}/service_account.json"

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

docker build -t {{ service.instance_name }}_toolbox \
-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 %}

docker_auth_var="AUTH_AUTO_DETECTED=false"
if [ -n "$TOOLBOX_GOOGLE_APPLICATION_CREDENTIALS" ]
then
    docker_auth_var="GOOGLE_APPLICATION_CREDENTIALS=$TOOLBOX_GOOGLE_APPLICATION_CREDENTIALS"
elif [ -n "$GOOGLE_AUTH_TOKEN" ]
then
    docker_auth_var="CLOUDSDK_AUTH_ACCESS_TOKEN=$GOOGLE_AUTH_TOKEN"
elif [ -n "$CLOUDSDK_AUTH_ACCESS_TOKEN" ]
then
    docker_auth_var="CLOUDSDK_AUTH_ACCESS_TOKEN=$CLOUDSDK_AUTH_ACCESS_TOKEN"
fi

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 \
-e "$docker_auth_var" \
{%- for variable in toolbox.environment_items -%}
-e {{ variable.name }}={{ shlex.quote(variable.value) }} \
{%- endfor -%}
--network ${CNC_TOOLBOX_NETWORK:-host} \
{%- if command %}
--rm {{ service.instance_name }}_toolbox -c '{{ command }}'; command_result=$?
{%- else %}
-it --rm {{ service.instance_name }}_toolbox
{%- endif %}

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