#!/usr/bin/env bash

region=$(curl --silent http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region)
echo "Detected region as ${region}"

ecr_region=${AWS_REGION:-$region}
echo "Will authenticate with ${ecr_region}"

while true; do
    info=$(aws ecr get-login --no-include-email --region ${ecr_region})

    user=$(echo ${info} | awk '{print $4}')
    password=$(echo ${info} | awk '{print $6}')
    token=$( echo "${user}:${password}" | base64 | tr -d "[:space:]" )

    url=$(echo ${info} | awk '{print $7}')
    host=$(python -c "print '${url}'[8:]")

    echo "Updating nginx configuration. Targeting ${url}"
    HOST=${host} TOKEN=${token} URL=${url} envsubst '$TOKEN $URL $HOST' < ./nginx.conf > /etc/nginx/nginx.conf

    if [[ -f "/run/nginx/nginx.pid" ]]; then
        echo "Reloading nginx";
        nginx -s reload
    else
        echo "Starting nginx";
        (nginx &)
    fi

    sleep 30m;
done
