#!/bin/bash

set -e

NAME=$1
if [ -z "$NAME" ]; then
  echo "Missing image name"
  exit 1
fi

SHA=$2
if [ -z "$SHA" ]; then
  echo "Missing git sha"
  exit 1
fi

DOCKERFILE=$3
if [ -z "$DOCKERFILE" ]; then
  echo "Missing dockerfile path"
  exit 1
fi

ECR=$4
if [ -z "$ECR" ]; then
  echo "Missing ECR endpoint"
  exit 1
fi

# Log into ECR
# https://forums.docker.com/t/docker-push-to-ecr-failing-with-no-basic-auth-credentials/17358
eval $(aws ecr get-login --region us-west-2 --no-include-email | sed 's|https://||')

# Build the Docker image
docker build -t $NAME:$SHA -f $DOCKERFILE .

# Push the Docker image with sha and latest tags
docker tag $NAME:$SHA $ECR/$NAME:$SHA
docker push $ECR/$NAME:$SHA
docker tag $NAME:$SHA $ECR/$NAME:latest
docker push $ECR/$NAME:latest
