#!/bin/bash
set -e

ADMIN_PANEL_URL="docker-registry.internal.justin.tv/admin-services/admin-panel:$GIT_COMMIT"
HTTP_REDIRECT_URL="docker-registry.internal.justin.tv/admin-services/admin-panel-http-redirect:$GIT_COMMIT"
BASE_STAGING_ECR_URL="219087926005.dkr.ecr.us-west-2.amazonaws.com/admin-panel-staging"
BASE_PROD_ECR_URL="196915980276.dkr.ecr.us-west-2.amazonaws.com/admin-panel-production"
BASE_CANARY_ECR_URL="196915980276.dkr.ecr.us-west-2.amazonaws.com/admin-panel-canary"
S2S_SIDECAR_URL="docker-registry.internal.justin.tv/sse/s2s-caller-sidecar:latest"
SANDSTORM_URL="docker-registry.internal.justin.tv/sse/sandstorm-sidecar"
ECS_REGION="us-west-2"

case $ENVIRONMENT in
  "staging")
    export ECR_ADMIN_PANEL_URL="$BASE_STAGING_ECR_URL:$GIT_COMMIT"
    export ECR_HTTP_REDIRECT_URL="$BASE_STAGING_ECR_URL:$GIT_COMMIT-http"
    export ECR_SANDSTORM_URL="$BASE_STAGING_ECR_URL:$GIT_COMMIT-sandstorm"
    export ECR_S2S_URL="$BASE_STAGING_ECR_URL:$GIT_COMMIT-s2s"
    export DEPLOY_ROLE_ARN="arn:aws:iam::219087926005:role/admin-panel-deploy-staging"
    ;;
  "production")
    export ECR_ADMIN_PANEL_URL="$BASE_PROD_ECR_URL:$GIT_COMMIT"
    export ECR_HTTP_REDIRECT_URL="$BASE_PROD_ECR_URL:$GIT_COMMIT-http"
    export ECR_SANDSTORM_URL="$BASE_PROD_ECR_URL:$GIT_COMMIT-sandstorm"
    export ECR_S2S_URL="$BASE_PROD_ECR_URL:$GIT_COMMIT-s2s"
    export DEPLOY_ROLE_ARN="arn:aws:iam::196915980276:role/admin-panel-deploy-production"
    ;;
  "canary")
    export ECR_ADMIN_PANEL_URL="$BASE_CANARY_ECR_URL:$GIT_COMMIT"
    export ECR_HTTP_REDIRECT_URL="$BASE_CANARY_ECR_URL:$GIT_COMMIT-http"
    export ECR_SANDSTORM_URL="$BASE_CANARY_ECR_URL:$GIT_COMMIT-sandstorm"
    export ECR_S2S_URL="$BASE_CANARY_ECR_URL:$GIT_COMMIT-s2s"
    export DEPLOY_ROLE_ARN="arn:aws:iam::196915980276:role/admin-panel-deploy-canary"
    ;;
  *)
    echo "Invalid Enviroment: $ENVIRONMENT"
    exit 1
    ;;
esac

docker pull $S2S_SIDECAR_URL
docker pull $ADMIN_PANEL_URL
docker pull $HTTP_REDIRECT_URL
docker pull $SANDSTORM_URL
docker tag $S2S_SIDECAR_URL $ECR_S2S_URL
docker tag $ADMIN_PANEL_URL $ECR_ADMIN_PANEL_URL
docker tag $HTTP_REDIRECT_URL $ECR_HTTP_REDIRECT_URL
docker tag $SANDSTORM_URL $ECR_SANDSTORM_URL

CREDS=($(aws sts assume-role \
  --role-arn "$DEPLOY_ROLE_ARN" \
  --role-session-name "admin-panel-deploy-${ENVIRONMENT}" \
  --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' \
  --output "text" \
  --duration-seconds 900 \
  --region ${ECS_REGION}))

AWS_ACCESS_KEY_ID=${CREDS[0]} AWS_SECRET_ACCESS_KEY=${CREDS[1]} AWS_SESSION_TOKEN=${CREDS[2]} aws ecr get-login --no-include-email --region "$ECS_REGION" | bash
docker push $ECR_ADMIN_PANEL_URL
docker push $ECR_S2S_URL
docker push $ECR_HTTP_REDIRECT_URL
docker push $ECR_SANDSTORM_URL

./bin/update-task-def && sleep 5 # give a chance to propagate the change before we start the watchdog
