#!/bin/bash
set -eo pipefail

[[ -z "$REPO" ]] && echo '$REPO is required' && exit 1

export PYTHONUNBUFFERED=1

export DELETE_USER_IMAGE_URL="$REPO:history-task-delete-user-$GIT_COMMIT"
export GENERATE_REPORT_IMAGE_URL="$REPO:history-task-generate-user-report-$GIT_COMMIT"
set -x

BASE_STAGING_ECR_URL="005087123760.dkr.ecr.us-west-2.amazonaws.com/history-service-v3-staging"
BASE_PROD_ECR_URL="958416494912.dkr.ecr.us-west-2.amazonaws.com/history-service-v3-prod"

case $ENVIRONMENT in
  "staging")
    export ECR_URL="$BASE_STAGING_ECR_URL"
    export ROLE_ARN="arn:aws:iam::005087123760:role/history-service-v3-staging-deploy"
    ;;
  "prod")
    export ECR_URL="$BASE_PROD_ECR_URL"
    export ROLE_ARN="arn:aws:iam::958416494912:role/history-service-v3-prod-deploy"
    ;;
  *)
    echo "Invalid Enviroment: $ENVIRONMENT"
    exit 1
    ;;
esac

export ECR_DELETE_USER_IMAGE_URL="$ECR_URL:delete-user-$GIT_COMMIT"
export ECR_GENERATE_REPORT_IMAGE_URL="$ECR_URL:generate-user-report-$GIT_COMMIT"

source ./scripts/assume-role.sh

docker pull $DELETE_USER_IMAGE_URL
docker tag $DELETE_USER_IMAGE_URL $ECR_DELETE_USER_IMAGE_URL

docker pull $GENERATE_REPORT_IMAGE_URL
docker tag $GENERATE_REPORT_IMAGE_URL $ECR_GENERATE_REPORT_IMAGE_URL

aws ecr get-login --no-include-email --region us-west-2 | bash
docker push $ECR_DELETE_USER_IMAGE_URL
docker push $ECR_GENERATE_REPORT_IMAGE_URL

# deploy ecs tasks
./bin/deploy ecs -env $ENVIRONMENT -git-commit $GIT_COMMIT

# upload lambda zip files to s3
./bin/deploy s3-upload-lambda -env $ENVIRONMENT -dir ./lambdas -git-commit $GIT_COMMIT

# update lambda func with s3 artifacts
./bin/deploy lambda -env $ENVIRONMENT -git-commit $GIT_COMMIT
