#!/bin/bash

ecr_repo=$1

function usage() {
    echo "Usage: $0 -n ECR_REPO_NAME -a ACCOUNT_ID -r REGION -g GO_VERSION"
    echo "Example. $0 -n raid-pipeline-ecr -a 641044725657 -r us-west-2 -g 1.9.2"
    exit 1
}

while test $# != 0
do
    case "$1" in
    -n) shift; ECR_REPO_NAME=$1 ;;
    -a) shift; ACCOUNT_ID=$1 ;;
    -r) shift; REGION=$1 ;;
    -g) shift; GO_VERSION=$1 ;;
    -h) usage ;;
    esac
    shift
done

if [ -z $ECR_REPO_NAME ] || [ -z $ACCOUNT_ID ] || [ -z $REGION ]; then
    usage
fi

if [ ! $(which aws) ]; then
    echo "This script requires the AWS CLI, please install before continuing"
    exit 1
fi

if [ ! $(which docker) ]; then
    echo "This script requires the Docker CLI, please install before continuing"
    exit 1
fi

echo "Running 'aws ecr get-login' to retrieve credentials to Amazon ECR"
login_cmd=$(aws ecr get-login --region $REGION --no-include-email)

ecr_endpoint="${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com"

echo "ep: ${ecr_endpoint}"
echo "Executing docker login cmd ${login_cmd}"
eval $login_cmd

echo "Retrieving docker image for golang $GO_VERSION"
docker pull golang:$GO_VERSION

echo "Tagging image to push to your repository"
docker tag golang:$GO_VERSION $ecr_endpoint/$ECR_REPO_NAME:golang$GO_VERSION

echo "Pushing docker iamge to ECR"
docker push $ecr_endpoint/$ECR_REPO_NAME:golang$GO_VERSION
