#!/bin/bash

# Generates temporary AWS credentials using your MFA device and creates a new 'orch_temp' AWS profile with them (12 hour duration).

# To use this script, you MUST have multiple AWS profiles specified in your ~/.aws/credentials file.
# Dev creds should be under a profile named 'orch_dev', and prod creds under 'orch_prod'
# This script will create a new profile named 'orch_temp'

# AWS credential file profile name prefix / suffix
# e.g. profile_prefix=orch_
profile_prefix=
profile_suffix=

# Create a master file (.store) that will act as the source of your AWS Prod and Dev credentials
if [ ! -f "${HOME}"/.aws/.store ]; then
  if [ -f "${HOME}"/.aws/credentials ]; then
    cp -a "${HOME}"/.aws/credentials "${HOME}"/.aws/.store
    echo "Credentials have been backed up and stored in ${HOME}/.aws/.store"
  else
    echo "There is no credentials file located in ${HOME}/.aws/credentials" && exit 1
  fi
else
# If the master file already exists, replace the configuration in credentials with .store, for AWS CLI to read your profile keys
  cp -a "${HOME}"/.aws/.store "${HOME}"/.aws/credentials
fi

if [ "$#" -eq 2 ]; then
  code=$2
  echo "Generating temp credentials for $1 AWS profile with provided one-time code."
elif [ "$#" -eq 1 ]; then
  echo "Generating temp credentials for $1 AWS profile."
else  
  echo "Please specify which AWS profile for which you are generating temp credentials. ([dev] or [prod])"
  return
fi

# Query IAM to get the username associated with the keys in the credentials file
username=$(AWS_DEFAULT_PROFILE=${profile_prefix}${1}${profile_suffix} aws iam get-user --query 'User.[UserName]' --output text)
if [ -z "${username}" ]
then
  echo "Can not identify who you are. "
  return
fi

echo You are: ${username}

# Query IAM to get the user's MFA device
device=$(AWS_DEFAULT_PROFILE=${profile_prefix}${1}${profile_suffix} aws iam list-mfa-devices --user-name "${username}" --query 'MFADevices[*].SerialNumber' --output text)
if [ -z "${device}" ]; then
  echo "Can not find any MFA device for you."
  return
fi

if [ -z "$code" ]; then
  echo "Your MFA device is:" ${device}
  read -p "Enter your MFA code now: " code
fi

# Use the MFA device to get a session token and query out the necessary credentials.
output=$(AWS_DEFAULT_PROFILE=${profile_prefix}${1}${profile_suffix} aws sts get-session-token --serial-number "${device}" --query 'Credentials.[SecretAccessKey,AccessKeyId,SessionToken,Expiration]' --output text --token-code ${code})
secret=$(echo $output | cut -f1 -d ' ')
access=$(echo $output | cut -f2 -d ' ')
session=$(echo $output | cut -f3 -d ' ')
expiration=$(echo $output | cut -f4 -d ' ')

if [ -z "${secret}" -o -z "${session}" -o -z "${access}" ]; then
  echo "Unable to get temporary credentials."
  return
fi

# Seed the credentials into a new temp default profile in .aws/credentials
echo "" >> "${HOME}"/.aws/credentials
echo "[${profile_prefix}temp${profile_suffix}]" >> "${HOME}"/.aws/credentials
echo "aws_access_key_id = ${access}" >> "${HOME}"/.aws/credentials
echo "aws_secret_access_key = ${secret}" >> "${HOME}"/.aws/credentials
echo "aws_session_token = ${session}" >> "${HOME}"/.aws/credentials

echo "Keys are valid until ${expiration}"
echo "Temporary credentials have been stored as a new '${profile_prefix}temp' profile in ${HOME}/.aws/credentials"
echo "Preface your aws commands with 'AWS_DEFAULT_PROFILE=${profile_prefix}temp' to use your new credentials with the aws CLI, or otherwise specify the '${profile_prefix}temp' profile in your preferred software."

# Export the profile to use it by default (disabled)
# export AWS_PROFILE=orch_temp
