REPO_NAME="dev-$USER-fibcow"

AWS_ACCOUNT_ID=103233932089
AWS_REGION=us-east-1

ECR_BASE="$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com"
ECR_REPO_BASE="$ECR_BASE/$REPO_NAME"

if [ -z "$1" ]; then
    echo '$1 - must be set as current tag version'
    exit 1
fi

if [ -z "$2" ]; then
    echo '$2 - must be set as cache tag version'
    exit 1
fi

NEW_TAG="$1"
CACHE_TAG="$2"
TARGET=${3:-function}

set -x

# create repo if not exists in AWS
aws ecr describe-repositories \
    --repository-names $REPO_NAME

if [ $? -ne 0 ]; then
    aws ecr create-repository \
        --repository-name $REPO_NAME \
        --image-scanning-configuration scanOnPush=true
fi

set -e

# log into docker client for aws
aws ecr get-login-password \
    --region $AWS_REGION | \
    docker login \
        --username AWS \
        --password-stdin $ECR_BASE

# remove cache to simulate new machine
docker builder prune \
    --filter label=project=cache_test \
    --all \
    -f

# ECR specific tags
NEW_ECR_TAG="$ECR_REPO_BASE:$NEW_TAG"
CACHE_ECR_TAG="$ECR_REPO_BASE:$CACHE_TAG"

# build image, adding ECR tag
docker build \
    --target $TARGET \
    --build-arg BUILDKIT_INLINE_CACHE=1 \
    --cache-from $CACHE_ECR_TAG \
    --progress plain \
    -t $NEW_ECR_TAG \
    .

# push to ECR
docker push $NEW_ECR_TAG
