AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Run the SecureContact Lambda in AWS

Parameters:
  ArtifactBucket:
    Description: Name of the S3 bucket where the artifact is located
    Type: String

  PublicBucketName:
    Description: Name to use for the public S3 bucket that will serve content
    Type: String

  Stage:
    Description: Application stage
    Type: String
    AllowedValues:
    - PROD
    - CODE
    - DEV
    Default: PROD

  App:
    Description: Application name
    Type: String
    Default: secure-contact-lambda

  Stack:
    Description: Application stack
    Type: String
    Default: secure-contact

Resources:

# ----------------------- #
#  S3 BUCKETS FOR APP     #
# ----------------------- #

  PublicBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Retain
    Properties:
      AccessControl: PublicRead
      BucketName: !Ref PublicBucketName
      LifecycleConfiguration:
        Rules:
          - ExpirationInDays: 7
            Status: Enabled
      WebsiteConfiguration:
        IndexDocument: index.html
        ErrorDocument: 404.html
      Tags:
        - Key: App
          Value: !Ref App
        - Key: Stack
          Value: !Ref Stack
        - Key: Stage
          Value: !Ref Stage

  PublicBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket:
        Ref: PublicBucket
      PolicyDocument:
        Statement:
        - Action:
          - s3:GetObject
          Effect: Allow
          Resource:
            - !Sub arn:aws:s3:::${PublicBucket}/*
          Principal: "*"

  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal: {Service: [lambda.amazonaws.com]}
            Action: ['sts:AssumeRole']
      Path: /
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
      Policies:
        - PolicyName: public-bucket-upload
          PolicyDocument:
            Statement:
              # grant access to the S3 bucket that will hold the website contents
              - Effect: Allow
                Resource: !Sub arn:aws:s3:::${PublicBucketName}
                Action:
                  - s3:ListBucket
              - Effect: Allow
                Resource: !Sub arn:aws:s3:::${PublicBucketName}/*
                Action:
                  - s3:PutObject
                  - s3:DeleteObject
