AWSTemplateFormatVersion: "2010-09-09"
Description: CloudFormation template for Hub HA setup

Parameters:
  VpcId:
    Type: String
    Description: VPC ID

  BaseResourceName:
    Type: String
    Description: Base Name for Hub HA Resources

  ClusterOIDCURL:
    Type: String
    Description: Cluster OIDC URL

Resources:
  # Role for EFS CSI Controller with OIDC
  EFSControllerRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument: !Sub
        - |
          {
            "Version": "2012-10-17",
            "Statement": [
              {
                "Effect": "Allow",
                "Principal": {
                  "Federated": "arn:aws:iam::${AWS::AccountId}:oidc-provider/${ClusterOIDCURL}"
                },
                "Action": "sts:AssumeRoleWithWebIdentity",
                "Condition": {
                  "StringEquals": {
                    "${ClusterOIDCURL}:aud": "sts.amazonaws.com",
                    "${ClusterOIDCURL}:sub": "system:serviceaccount:kube-system:efs-csi-controller-sa"
                  }
                }
              }
            ]
          }
        - { "ClusterOIDCURL": !Ref ClusterOIDCURL }
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/service-role/AmazonEFSCSIDriverPolicy"
      Path: "/"
      Tags: []

  # Security Group for EFS
  EFSSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: !Sub "${BaseResourceName}-SG"
      GroupDescription: "Security group for EFS"
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - IpProtocol: "-1"
          CidrIp: "0.0.0.0/0"

  # EFS File System
  EFSFileSystem:
    Type: AWS::EFS::FileSystem
    Properties:
      PerformanceMode: generalPurpose
      Encrypted: true
      ThroughputMode: elastic
      FileSystemTags:
        - Key: Name
          Value: !Sub "${BaseResourceName}-EFS"

Outputs:
  EFSControllerRoleArn:
    Value: !GetAtt EFSControllerRole.Arn
    Description: The ARN of the EFS Controller Role

  EFSSecurityGroup:
    Value: !Ref EFSSecurityGroup
    Description: The Group ID of the EFS Security Group

  EFSFileSystemId:
    Value: !Ref EFSFileSystem
    Description: The ID of the created EFS file system
