#!/bin/bash

# Prompt the user to enter the IAM role name
read -p "Enter the IAM role name you want to create: " ROLE_NAME

# Check if the role name is not empty
if [[ -z "$ROLE_NAME" ]]; then
  echo "Role name cannot be empty. Please run the script again and enter a valid role name."
  exit 1
fi

# Array of policies to attach to the role
ROLE_POLICIES=(
  "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
)

# Disable pager for AWS CLI commands to avoid opening the vi editor
export AWS_PAGER=""

# Define the trust policy for the role (example for EC2 service)
TRUST_POLICY='{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ssm.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    },
    {
      "Effect": "Allow",
      "Principal": {
          "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}'

# Create a temporary file for the trust policy
echo "$TRUST_POLICY" > trust-policy.json

# Create the IAM role
echo "Creating IAM role: $ROLE_NAME"
aws iam create-role --role-name "$ROLE_NAME" --assume-role-policy-document file://trust-policy.json

# Check if the role creation was successful
if [[ $? -ne 0 ]]; then
  echo "Failed to create role. Please check AWS CLI configuration and permissions."
  rm -f trust-policy.json
  exit 1
fi

# Attach policies to the role
for POLICY_ARN in "${ROLE_POLICIES[@]}"; do
  echo "Attaching policy: $POLICY_ARN to role: $ROLE_NAME"
  aws iam attach-role-policy --role-name "$ROLE_NAME" --policy-arn "$POLICY_ARN"

  # Check if the policy attachment was successful
  if [[ $? -ne 0 ]]; then
    echo "Failed to attach policy: $POLICY_ARN to the role. Please check your permissions."
  fi

# Create Instance Profile
echo "Creating instance profile: $ROLE_NAME"
aws iam create-instance-profile --instance-profile-name "$ROLE_NAME"

# Check if the instance profile creation was successful
if [[ $? -ne 0 ]]; then
  echo "Failed to create instance profile. Please check AWS CLI configuration and permissions."
  rm -f trust-policy.json
  exit 1
fi

# Add role to instance profile
echo "Adding role: $ROLE_NAME to instance profile: $ROLE_NAME"
aws iam add-role-to-instance-profile --role-name "$ROLE_NAME" --instance-profile-name "$ROLE_NAME"

# Check if the role addition was successful
if [[ $? -ne 0 ]]; then
  echo "Failed to add role to instance profile. Please check your permissions."
fi

done

# Merge access keys and role ARN to a single file
echo "{
  \"RoleARN\": \"arn:aws:iam::$(aws sts get-caller-identity --query Account --output text):role/$ROLE_NAME\"
}" > "${ROLE_NAME}_role_arn.json"

# Cleanup
rm -f trust-policy.json

echo "Script completed successfully. IAM user and role created with specified policies."