#!/bin/bash
 
# --- Configuration ---
# 1. The profile used for the initial `aws-azure-login` command
AZURE_PROFILE="default"
 
# 2. The profile you specify in the `aws sts assume-role` command
ASSUME_ROLE_PROFILE="role to assume" 
 
# The full ARN of the final role you need to assume
ROLE_TO_ASSUME_ARN="arn:aws:iam::123456789012:role/YourFinalRole" 
 
# The session name for the final assumed role
SESSION_NAME="EKSPentestSession"
 
# The profile in ~/.aws/credentials to write the final credentials to
TARGET_PROFILE="default"
 
# The target EKS cluster for kubeconfig
CLUSTER="cluster"
# --- End Configuration ---
 
# Must have configured Azure profile first - 
echo "Running aws-azure-login with profile '$AZURE_PROFILE'..."
aws-azure-login --profile "$AZURE_PROFILE" --no-prompt --no-sandbox
if [ $? -ne 0 ]; then
    echo "aws-azure-login failed. Aborting."
    exit 1
fi
 
echo "Assuming final role using profile '$ASSUME_ROLE_PROFILE'..."
ASSUMED_ROLE_JSON=$(aws sts assume-role \
    --role-arn "$ROLE_TO_ASSUME_ARN" \
    --role-session-name "$SESSION_NAME" \
    --profile "$ASSUME_ROLE_PROFILE")
 
if [ $? -ne 0 ]; then
    echo "sts:AssumeRole failed. Check the ARN and profile permissions. Aborting."
    exit 1
fi
 
ACCESS_KEY_ID=$(echo "$ASSUMED_ROLE_JSON" | jq -r '.Credentials.AccessKeyId')
SECRET_ACCESS_KEY=$(echo "$ASSUMED_ROLE_JSON" | jq -r '.Credentials.SecretAccessKey')
SESSION_TOKEN=$(echo "$ASSUMED_ROLE_JSON" | jq -r '.Credentials.SessionToken')
 
echo "Updating credentials for profile '$TARGET_PROFILE'..."
aws configure set aws_access_key_id "$ACCESS_KEY_ID" --profile "$TARGET_PROFILE"
aws configure set aws_secret_access_key "$SECRET_ACCESS_KEY" --profile "$TARGET_PROFILE"
aws configure set aws_session_token "$SESSION_TOKEN" --profile "$TARGET_PROFILE"
 
echo "Credentials updated."
 
# Update kubeconfig (DON'T use --profile, default creds are now assumed role) 
aws eks update-kubeconfig --name "$CLUSTER" --region eu-west-2 #--profile "$ASSUME_ROLE_PROFILE" (this shouldn't be needed)
echo "kubeconfig context updated, you are running as..."
aws sts get-caller-identity