#!/bin/bash
set -eo pipefail

[[ -z "$ENVIRONMENT" ]] && echo '$ENVIRONMENT is required' && exit 1
[[ -z "$LAMBDA_FN" ]] && echo '$LAMBDA_FN is required' && exit 1
[[ -z "$LAMBDA_ZIP" ]] && echo '$LAMBDA_ZIP is required' && exit 1

case $ENVIRONMENT in
testing)
  ACCOUNT_ID="219087926005"
  ;;
staging)
  ACCOUNT_ID="219087926005"
  ;;
production)
  ACCOUNT_ID="196915980276"
  ;;
*)
  echo "invalid ENVIRONMENT: $ENVIRONMENT" && exit 1
  ;;
esac

ROLE_ARN="arn:aws:iam::$ACCOUNT_ID:role/admin-panel/$ENVIRONMENT/deploy/admin-panel-$ENVIRONMENT-$LAMBDA_FN-deploy"

echo "assuming $ROLE_ARN"
CREDS=(`aws sts assume-role \
  --role-arn "$ROLE_ARN" \
  --role-session-name "jenkins-deploy-lambdas" \
  --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' \
  --output "text" \
  --duration-seconds 900`)

export AWS_ACCESS_KEY_ID=${CREDS[0]}
export AWS_SECRET_ACCESS_KEY=${CREDS[1]}
export AWS_SESSION_TOKEN=${CREDS[2]}

aws lambda update-function-code \
  --publish \
  --region us-west-2 \
  --function-name admin-panel-$ENVIRONMENT-$LAMBDA_FN \
  --zip-file fileb://$LAMBDA_ZIP
