AWSTemplateFormatVersion: '2010-09-09'
Description: 'TrailTool Sandbox - Creates CloudTrail trail, S3 bucket, and EventBridge forwarding'

Parameters:
  UserEmail:
    Type: String
    Description: Email address for TrailTool registration and notifications

  TrailToolAccountId:
    Type: String
    Description: AWS Account ID where TrailTool is deployed (use your account ID for self-hosted, or 468087121425 for SaaS)
    Default: '468087121425'

  TrailName:
    Type: String
    Description: Name for the CloudTrail trail
    Default: 'trailtool-trail'

  IsMultiRegionTrail:
    Type: String
    Description: Enable multi-region trail
    Default: 'true'
    AllowedValues: ['true', 'false']

Resources:
  # ===================================================================
  # S3 BUCKET - CloudTrail logs storage
  # ===================================================================

  CloudTrailBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub 'trailtool-cloudtrail-${AWS::AccountId}-${AWS::Region}'
      VersioningConfiguration:
        Status: Enabled
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      LifecycleConfiguration:
        Rules:
          - Id: DeleteOldLogs
            Status: Enabled
            ExpirationInDays: 90
      NotificationConfiguration:
        EventBridgeConfiguration:
          EventBridgeEnabled: true
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true

  # ===================================================================
  # S3 BUCKET POLICY - CloudTrail write + TrailTool read permissions
  # ===================================================================

  CloudTrailBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref CloudTrailBucket
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          # CloudTrail service permissions
          - Sid: AWSCloudTrailAclCheck
            Effect: Allow
            Principal:
              Service: cloudtrail.amazonaws.com
            Action: s3:GetBucketAcl
            Resource: !GetAtt CloudTrailBucket.Arn

          - Sid: AWSCloudTrailWrite
            Effect: Allow
            Principal:
              Service: cloudtrail.amazonaws.com
            Action: s3:PutObject
            Resource: !Sub '${CloudTrailBucket.Arn}/AWSLogs/${AWS::AccountId}/*'
            Condition:
              StringEquals:
                s3:x-amz-acl: bucket-owner-full-control

          # TrailTool read permissions
          - Sid: TrailToolReadAccess
            Effect: Allow
            Principal:
              AWS: !Sub 'arn:aws:iam::${TrailToolAccountId}:root'
            Action:
              - s3:GetObject
              - s3:ListBucket
            Resource:
              - !GetAtt CloudTrailBucket.Arn
              - !Sub '${CloudTrailBucket.Arn}/*'

  # ===================================================================
  # CLOUDTRAIL - Multi-region trail with log file validation
  # ===================================================================

  CloudTrail:
    Type: AWS::CloudTrail::Trail
    DependsOn: CloudTrailBucketPolicy
    Properties:
      TrailName: !Ref TrailName
      S3BucketName: !Ref CloudTrailBucket
      IsLogging: true
      IsMultiRegionTrail: !Ref IsMultiRegionTrail
      IncludeGlobalServiceEvents: true
      EnableLogFileValidation: true

  # ===================================================================
  # EVENTBRIDGE RULE - Invoke TrailTool ingestor on S3 events
  # ===================================================================

  CloudTrailEventsRule:
    Type: AWS::Events::Rule
    Properties:
      Name: trailtool-cloudtrail-forwarding
      Description: Invoke TrailTool ingestor Lambda on CloudTrail S3 events
      EventPattern:
        source:
          - aws.s3
        detail-type:
          - Object Created
        detail:
          bucket:
            name:
              - !Ref CloudTrailBucket
          object:
            key:
              - prefix: AWSLogs/
              - suffix: .json.gz
      State: ENABLED
      Targets:
        - Arn: !Sub 'arn:aws:lambda:${AWS::Region}:${TrailToolAccountId}:function:trailtool-ingestor'
          Id: TrailToolIngestor
          RoleArn: !GetAtt EventBridgeInvokeRole.Arn

  # IAM Role for EventBridge to invoke cross-account Lambda
  EventBridgeInvokeRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: TrailToolEventBridgeInvokeRole
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: events.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: InvokeTrailToolLambda
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: lambda:InvokeFunction
                Resource: !Sub 'arn:aws:lambda:${AWS::Region}:${TrailToolAccountId}:function:trailtool-ingestor'

  # ===================================================================
  # REGISTRATION WITH TRAILTOOL
  # ===================================================================

  TrailToolRegistration:
    Type: Custom::TrailToolRegistration
    DependsOn:
      - CloudTrailEventsRule
      - CloudTrail
    Properties:
      ServiceToken: !Sub 'arn:aws:lambda:${AWS::Region}:${TrailToolAccountId}:function:trailtool-onboard'
      UserEmail: !Ref UserEmail
      CloudTrailBucket: !Ref CloudTrailBucket
      CloudTrailAccount: !Ref 'AWS::AccountId'
      ManagementAccountId: !Ref 'AWS::AccountId'
      EventBridgeRuleArn: !GetAtt CloudTrailEventsRule.Arn

Outputs:
  CustomerId:
    Description: Your TrailTool customer ID
    Value: !GetAtt TrailToolRegistration.CustomerId

  CloudTrailBucketName:
    Description: S3 bucket for CloudTrail logs
    Value: !Ref CloudTrailBucket

  TrailArn:
    Description: CloudTrail trail ARN
    Value: !GetAtt CloudTrail.Arn

  EventBridgeRuleArn:
    Description: ARN of the EventBridge rule forwarding to TrailTool
    Value: !GetAtt CloudTrailEventsRule.Arn

  MagicLinkSent:
    Description: Next steps
    Value: Check your email for login link
