AWSTemplateFormatVersion: '2010-09-09'
Description: 'CloudFormation template for Cequence API Gateway'

Parameters:
  Region:
    Type: String
    Default: us-west-2
  ApiGatewayId:
    Type: String
  Stage:
    Type: String
  LambdaFunctionName:
    Type: String
    Default: cequence_log_aggregator
  ApiUrl:
    Type: String
  AuthApiUrl:
    Type: String
  ClientId:
    Type: String
  ClientSecret:
    Type: String
    NoEcho: true
  GrantType:
    Type: String
    Default: client_credentials
  TimeDelay:
    Type: String
    Default: '1'
  TimeZone:
    Type: String
    Default: America/Los_Angeles
  TokenCacheName:
    Type: String
    Default: test-cequence-auth-token
  SsmParameterValue:
    Type: String
    Default: '{"token": "eyJhbGciOiJSUz", "storage_time": "2024-10-05 09:49:42.629310-07:00"}'
  LambdaRoleName:
    Type: String
    Default: cequence_lambda_execution_role
  LambdaLogGroupName:
    Type: String
    Default: /aws/lambda/cequence_log_aggregator
  LambdaTimeout:
    Type: Number
    Default: 300
  EventBridgeRuleName:
    Type: String
    Default: cequence-plugin-log-scheduler
  EventBridgeSchedule:
    Type: String
    Default: rate(1 minute)

Resources:
  CequenceAuthToken:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Ref TokenCacheName
      Type: String
      Value: !Ref SsmParameterValue
      Description: Token for Cequence authentication
      Tier: Standard

  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Ref LambdaRoleName
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: LambdaPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                  - logs:FilterLogEvents
                  - logs:GetLogEvents
                  - ssm:GetParameter
                  - ssm:PutParameter
                Resource: '*'

  CequenceLogAggregator:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Ref LambdaFunctionName
      Handler: log_aggregator.aggregate_logs
      Runtime: python3.9
      Role: !GetAtt LambdaExecutionRole.Arn
      Code:
        ZipFile: cequence_plugin.zip
      Environment:
        Variables:
          API_URL: !Ref ApiUrl
          AUTH_API_URL: !Ref AuthApiUrl
          CLIENT_ID: !Ref ClientId
          CLIENT_SECRET: !Ref ClientSecret
          GRANT_TYPE: !Ref GrantType
          LOG_GROUP_NAME: !Sub API-Gateway-Execution-Logs_${ApiGatewayId}/${Stage}
          REGION: !Ref Region
          STAGE: !Ref Stage
          TIME_DELAY: !Ref TimeDelay
          TIME_ZONE: !Ref TimeZone
          TOKEN_CACHE_NAME: !Ref TokenCacheName
      Timeout: !Ref LambdaTimeout

  LambdaLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Ref LambdaLogGroupName
      RetentionInDays: 14

  EveryMinuteRule:
    Type: AWS::Events::Rule
    Properties:
      Name: !Ref EventBridgeRuleName
      Description: Fires every 1 minute
      ScheduleExpression: !Ref EventBridgeSchedule
      Targets:
        - Id: TriggerLambda
          Arn: !GetAtt CequenceLogAggregator.Arn

  LambdaPermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref CequenceLogAggregator
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt EveryMinuteRule.Arn

Outputs:
  ApiGatewayLogGroupName:
    Description: Name of the CloudWatch Log Group for API Gateway logs
    Value: !Sub API-Gateway-Execution-Logs_${ApiGatewayId}/${Stage}
  EventBridgeRuleName:
    Description: Name of the EventBridge rule
    Value: !Ref EveryMinuteRule
  LambdaFunctionName:
    Description: Name of the target Lambda function
    Value: !Ref CequenceLogAggregator
