#!/usr/bin/env bash

# check for the environment variable called AWS_PROFILES
# if it is set read it and generate AWS CLI config
if [[ -n "${AWS_PROFILES}"  ]];
then
  # create AWS configuration folder for Atlantis user
  mkdir -p "/home/atlantis/.aws/"

  EXTERNAL_ID=${STS_EXTERNAL_ID:-"atlantis"}

  # create the default profile
  cat << EOF > /home/atlantis/.aws/config
[default]
output = json
region = us-east-1

EOF

  IFS=';' read -ra profiles <<< "${AWS_PROFILES}"

  for line in "${profiles[@]}";
  do
    IFS=',' read -ra profile <<< "${line}"

    profile_name="${profile[0]}"
    role_arn="${profile[1]}"
    region="${profile[2]:-us-east-1}"
    output="${profile[3]:-json}"

  cat << EOF >> /home/atlantis/.aws/config
[profile ${profile_name}]
role_arn = ${role_arn}
credential_source = EcsContainer
output = ${output}
region = ${region}
role_session_name = atlantis
external_id = ${EXTERNAL_ID}
EOF
  done
fi

exec docker-entrypoint.sh "$@"
