#!/bin/bash
set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo -e "${GREEN}🔍 Verifying IAM Trust Policies for Pipeline Execution Roles${NC}"
echo ""

# Source the .env file
if [ -f .env ]; then
    export $(cat .env | grep -v '^#' | xargs)
else
    echo -e "${RED}Error: .env file not found${NC}"
    exit 1
fi

# Function to extract role name from ARN
get_role_name() {
    echo "$1" | awk -F'/' '{print $NF}'
}

# Function to verify trust policy
verify_trust_policy() {
    local ROLE_ARN=$1
    local ENVIRONMENT=$2
    local AWS_PROFILE=$3

    ROLE_NAME=$(get_role_name "$ROLE_ARN")
    echo -e "${CYAN}=== $ENVIRONMENT Role: $ROLE_NAME ===${NC}"
    echo -e "Profile: ${AWS_PROFILE}"

    # Get the current trust policy
    aws iam get-role \
        --role-name "$ROLE_NAME" \
        --profile $AWS_PROFILE \
        --query 'Role.AssumeRolePolicyDocument' \
        --output json 2>/dev/null | jq '.' || {
            echo -e "${RED}Failed to retrieve trust policy${NC}"
            return 1
        }

    # Check if GitHub OIDC is configured
    echo -e "\n${YELLOW}GitHub OIDC Configuration:${NC}"
    aws iam get-role \
        --role-name "$ROLE_NAME" \
        --profile $AWS_PROFILE \
        --query 'Role.AssumeRolePolicyDocument.Statement[?Principal.Federated != null] | [?contains(Principal.Federated, `token.actions.githubusercontent.com`)]' \
        --output json 2>/dev/null | jq '.' || echo "No GitHub OIDC configuration found"

    echo ""
}

# Verify available roles
if [ -n "$TESTING_PIPELINE_EXECUTION_ROLE" ]; then
    echo -e "${GREEN}=== Testing Environment ===${NC}"
    verify_trust_policy "$TESTING_PIPELINE_EXECUTION_ROLE" "Testing" "default"
fi

if [ -n "$STAGING_PIPELINE_EXECUTION_ROLE" ]; then
    echo -e "${GREEN}=== Staging Environment ===${NC}"
    verify_trust_policy "$STAGING_PIPELINE_EXECUTION_ROLE" "Staging" "default"
fi

if [ -n "$PROD_PIPELINE_EXECUTION_ROLE" ]; then
    echo -e "${GREEN}=== Production Environment ===${NC}"
    verify_trust_policy "$PROD_PIPELINE_EXECUTION_ROLE" "Production" "aillc"
fi

echo -e "${GREEN}✅ Verification complete!${NC}"
echo ""
echo -e "${YELLOW}What to look for:${NC}"
echo "1. The trust policy should have a Statement with GitHub OIDC principal"
echo "2. The Condition should include:"
echo "   - token.actions.githubusercontent.com:sub with patterns for:"
echo "     - repo:${GH_ACCOUNT}/${GH_REPO}:ref:refs/heads/main"
echo "     - repo:${GH_ACCOUNT}/${GH_REPO}:ref:refs/heads/feat/*"
echo "     - repo:${GH_ACCOUNT}/${GH_REPO}:ref:refs/heads/fix/*"
echo "     - repo:${GH_ACCOUNT}/${GH_REPO}:ref:refs/heads/docs/*"
echo "     - repo:${GH_ACCOUNT}/${GH_REPO}:ref:refs/heads/refactor/*"
echo "     - repo:${GH_ACCOUNT}/${GH_REPO}:ref:refs/heads/test/*"
echo "     - repo:${GH_ACCOUNT}/${GH_REPO}:ref:refs/heads/chore/*"
echo "     - repo:${GH_ACCOUNT}/${GH_REPO}:ref:refs/heads/perf/*"
echo "     - repo:${GH_ACCOUNT}/${GH_REPO}:pull_request"
