AWSTemplateFormatVersion: '2010-09-09'
Description: 'Solar kernel onboarding stack: scanner role plus billing export bootstrap'

Parameters:
  TrustedPrincipalArn:
    Type: String
    Description: 'The Solar principal that can assume the scanner role'
  ExternalId:
    Type: String
    Description: 'External ID used by Solar when assuming roles'
  ScannerRoleName:
    Type: String
    Default: 'SolarCloudScanner'
    Description: 'Name of the read-only scanner role'
  BillingExportPrefix:
    Type: String
    Default: 'solar/billing/cur2'
    Description: 'Prefix inside the billing export bucket for CUR 2.0 files'
  BillingExportBucketName:
    Type: String
    Default: ''
    Description: 'Optional S3 bucket name for billing exports. Leave blank to let CloudFormation name it.'
  EnableDiagnostics:
    Type: String
    Default: 'false'
    AllowedValues: ['true', 'false']
    Description: 'Optionally allow bounded metadata and metrics investigations. Log and secret contents remain inaccessible.'

Conditions:
  UseCustomBillingBucketName: !Not [!Equals [!Ref BillingExportBucketName, '']]
  DiagnosticsEnabled: !Equals [!Ref EnableDiagnostics, 'true']

Resources:
  ScannerRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Ref ScannerRoleName
      Description: 'Solar least-privilege scanner role with optional billing and diagnostics capabilities'
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              AWS: !Ref TrustedPrincipalArn
            Action: 'sts:AssumeRole'
            Condition:
              StringEquals:
                'sts:ExternalId': !Ref ExternalId
      Policies:
        - PolicyName: SolarInventoryReadOnlyV1
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: SupportedInventory
                Effect: Allow
                Action:
                  - 'apigateway:GET'
                  - 'cloudformation:DescribeStacks'
                  - 'cloudformation:ListStacks'
                  - 'cloudwatch:GetMetricData'
                  - 'config:DescribeConfigurationRecorders'
                  - 'config:DescribeConfigurationRecorderStatus'
                  - 'config:DescribeDeliveryChannels'
                  - 'cloudfront:ListDistributions'
                  - 'dynamodb:DescribeTable'
                  - 'dynamodb:ListTables'
                  - 'ec2:DescribeInstances'
                  - 'ec2:DescribeRegions'
                  - 'ec2:DescribeSecurityGroups'
                  - 'ec2:DescribeSubnets'
                  - 'ec2:DescribeVolumes'
                  - 'ec2:DescribeVpcs'
                  - 'ecr:DescribeImages'
                  - 'ecr:DescribeRepositories'
                  - 'ecs:DescribeClusters'
                  - 'ecs:DescribeServices'
                  - 'ecs:ListClusters'
                  - 'ecs:ListServices'
                  - 'elasticloadbalancing:DescribeLoadBalancers'
                  - 'elasticloadbalancing:DescribeTargetGroups'
                  - 'elasticloadbalancing:DescribeTargetHealth'
                  - 'iam:ListRoles'
                  - 'iot:ListThings'
                  - 'kafka:ListClustersV2'
                  - 'lambda:ListFunctions'
                  - 'lambda:ListEventSourceMappings'
                  - 'logs:DescribeLogGroups'
                  - 'rds:DescribeDBInstances'
                  - 'route53:ListHostedZones'
                  - 'route53:ListResourceRecordSets'
                  - 's3:GetBucketLocation'
                  - 's3:ListAllMyBuckets'
                  - 'sns:ListTopics'
                  - 'sqs:ListQueues'
                  - 'tag:GetResources'
                Resource: '*'
              - Sid: VerifyScannerRolePolicy
                Effect: Allow
                Action:
                  - 'iam:GetRole'
                  - 'iam:GetRolePolicy'
                  - 'iam:ListAttachedRolePolicies'
                  - 'iam:ListRolePolicies'
                Resource: !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/${ScannerRoleName}'
        - PolicyName: SolarBillingReadOnlyV1
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: CostExplorerRead
                Effect: Allow
                Action:
                  - 'ce:GetCostAndUsage'
                  - 'ce:GetCostForecast'
                Resource: '*'
              - Sid: BillingExportList
                Effect: Allow
                Action:
                  - 's3:ListBucket'
                Resource: !GetAtt BillingExportBucket.Arn
                Condition:
                  StringLike:
                    's3:prefix':
                      - !Ref BillingExportPrefix
                      - !Sub '${BillingExportPrefix}/*'
              - Sid: BillingExportObjects
                Effect: Allow
                Action:
                  - 's3:GetObject'
                Resource: !Sub '${BillingExportBucket.Arn}/${BillingExportPrefix}/*'
        - PolicyName: SolarSelfCleanupV1
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: VerifyAndEmptySolarBillingBucket
                Effect: Allow
                Action:
                  - 's3:DeleteBucket'
                  - 's3:DeleteBucketPolicy'
                  - 's3:GetBucketTagging'
                  - 's3:GetBucketPolicy'
                  - 's3:ListBucket'
                  - 's3:ListBucketVersions'
                Resource: !GetAtt BillingExportBucket.Arn
              - Sid: DeleteSolarBillingObjects
                Effect: Allow
                Action:
                  - 's3:DeleteObject'
                  - 's3:DeleteObjectVersion'
                Resource: !Sub '${BillingExportBucket.Arn}/*'
              - Sid: DeleteSolarBillingExport
                Effect: Allow
                Action:
                  - 'bcm-data-exports:DeleteExport'
                Resource: !GetAtt BillingCur2Export.ExportArn
              - Sid: DeleteSolarScannerRole
                Effect: Allow
                Action:
                  - 'iam:DeleteRole'
                  - 'iam:DeleteRolePolicy'
                  - 'iam:DetachRolePolicy'
                  - 'iam:TagRole'
                  - 'iam:UntagRole'
                Resource: !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/${ScannerRoleName}'
              - Sid: DeleteOnlyThisOnboardingStack
                Effect: Allow
                Action:
                  - 'cloudformation:DeleteStack'
                  - 'cloudformation:DescribeStackResources'
                Resource: !Sub 'arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/${AWS::StackName}/*'
        - !If
          - DiagnosticsEnabled
          - PolicyName: SolarDiagnosticsReadOnlyV1
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Sid: BoundedDiagnostics
                  Effect: Allow
                  Action:
                    - 'cloudformation:ListStacks'
                    - 'cloudfront:GetDistribution'
                    - 'cloudtrail:LookupEvents'
                    - 'cloudwatch:DescribeAlarms'
                    - 'cloudwatch:GetMetricData'
                    - 'cloudwatch:GetMetricStatistics'
                    - 'ec2:DescribeInstanceStatus'
                    - 'ec2:DescribeInternetGateways'
                    - 'ec2:DescribeNatGateways'
                    - 'ec2:DescribeNetworkInterfaces'
                    - 'ec2:DescribeRouteTables'
                    - 'ecr:ListImages'
                    - 'eks:DescribeCluster'
                    - 'eks:ListClusters'
                    - 'elasticache:DescribeCacheClusters'
                    - 'elasticache:DescribeReplicationGroups'
                    - 'elasticloadbalancing:DescribeTargetGroups'
                    - 'elasticloadbalancing:DescribeTargetHealth'
                    - 'events:DescribeRule'
                    - 'events:ListRules'
                    - 'events:ListTargetsByRule'
                    - 'kafka:DescribeClusterV2'
                    - 'rds:DescribeDBClusters'
                    - 'sns:GetTopicAttributes'
                    - 'sqs:GetQueueAttributes'
                  Resource: '*'
          - !Ref AWS::NoValue
      Tags:
        - Key: Name
          Value: !Ref ScannerRoleName
        - Key: ManagedBy
          Value: SolarCloud
        - Key: Purpose
          Value: Scanner

  BillingExportBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !If
        - UseCustomBillingBucketName
        - !Ref BillingExportBucketName
        - !Ref AWS::NoValue
      OwnershipControls:
        Rules:
          - ObjectOwnership: BucketOwnerEnforced
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      VersioningConfiguration:
        Status: Enabled
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      Tags:
        - Key: ManagedBy
          Value: SolarCloud
        - Key: Purpose
          Value: BillingExport

  BillingExportBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref BillingExportBucket
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: AllowBillingDataExportsWrite
            Effect: Allow
            Principal:
              Service: 'bcm-data-exports.amazonaws.com'
            Action:
              - 's3:PutObject'
              - 's3:PutObjectAcl'
            Resource: !Sub '${BillingExportBucket.Arn}/*'
            Condition:
              StringEquals:
                aws:SourceAccount: !Ref AWS::AccountId
              StringLike:
                aws:SourceArn: !Sub 'arn:${AWS::Partition}:bcm-data-exports:${AWS::Region}:${AWS::AccountId}:export/*'
          - Sid: AllowBillingDataExportsBucketChecks
            Effect: Allow
            Principal:
              Service: 'bcm-data-exports.amazonaws.com'
            Action:
              - 's3:GetBucketAcl'
              - 's3:GetBucketPolicy'
              - 's3:GetBucketLocation'
              - 's3:ListBucket'
            Resource: !GetAtt BillingExportBucket.Arn
            Condition:
              StringEquals:
                aws:SourceAccount: !Ref AWS::AccountId
              StringLike:
                aws:SourceArn: !Sub 'arn:${AWS::Partition}:bcm-data-exports:${AWS::Region}:${AWS::AccountId}:export/*'

  BillingCur2Export:
    Type: AWS::BCMDataExports::Export
    DependsOn:
      - BillingExportBucketPolicy
    Properties:
      Export:
        Name: !Sub '${AWS::StackName}-billing-cur2'
        Description: 'Solar billing bootstrap export for CUR 2.0 data'
        DataQuery:
          QueryStatement: >
            SELECT bill_billing_period_start_date,
            line_item_usage_start_date,
            line_item_product_code,
            line_item_usage_account_id,
            product_region_code,
            pricing_unit,
            line_item_usage_amount,
            line_item_unblended_cost
            FROM COST_AND_USAGE_REPORT
          TableConfigurations:
            COST_AND_USAGE_REPORT:
              TIME_GRANULARITY: DAILY
              INCLUDE_RESOURCES: 'FALSE'
              INCLUDE_MANUAL_DISCOUNT_COMPATIBILITY: 'FALSE'
              INCLUDE_SPLIT_COST_ALLOCATION_DATA: 'FALSE'
        DestinationConfigurations:
          S3Destination:
            S3Bucket: !Ref BillingExportBucket
            S3Prefix: !Ref BillingExportPrefix
            S3Region: !Ref AWS::Region
            S3OutputConfigurations:
              Compression: GZIP
              Format: TEXT_OR_CSV
              OutputType: CUSTOM
              Overwrite: CREATE_NEW_REPORT
        RefreshCadence:
          Frequency: SYNCHRONOUS
      Tags:
        - Key: ManagedBy
          Value: SolarCloud
        - Key: Purpose
          Value: BillingExport

Outputs:
  RoleArn:
    Description: 'ARN of the Solar scanner role'
    Value: !GetAtt ScannerRole.Arn
    Export:
      Name: !Sub '${AWS::StackName}-RoleArn'

  BillingBootstrapMode:
    Description: 'How Solar should bootstrap billing for this account'
    Value: 'data_exports_cur2'

  ScannerPolicyContractVersion:
    Description: 'Version of the Solar least-privilege scanner policy contract'
    Value: 'solar-scanner-policy.v2'

  BillingExportBucket:
    Description: 'Bucket containing Solar billing export artifacts'
    Value: !Ref BillingExportBucket

  BillingExportPrefix:
    Description: 'Prefix used for Solar billing export artifacts'
    Value: !Ref BillingExportPrefix

  BillingExportArn:
    Description: 'ARN of the billing export resource'
    Value: !GetAtt BillingCur2Export.ExportArn
