AWSTemplateFormatVersion: "2010-09-09"
Parameters:
  DynamoDbArn:
    Type: String
    Default: "arn:aws:dynamodb:us-west-2:840161740319:table/tcat-workshop-quiz"
  S3BucketName:
    Type: String
  S3KeyPrefix:
    Type: String
    Default: taskcat-workshop-survey/
Conditions:
  InternalDynamo: !Equals [!Ref DynamoDbArn, ""]
Resources:
  CopyZips:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: !Sub "https://${S3BucketName}.s3.amazonaws.com/${S3KeyPrefix}templates/copy-zips.template.yaml"
      Parameters:
        S3BucketName: !Ref S3BucketName
        S3KeyPrefix: !Ref S3KeyPrefix
        SourceObjects: "lambda_functions/packages/Survey/lambda.zip,lambda_functions/packages/SurveySubmit/lambda.zip"
  SurveyRole:
    Type: AWS::IAM::Role
    Properties:
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Action:
              - sts:AssumeRole
            Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
  ServerlessRestApiProdStage:
    Type: AWS::ApiGateway::Stage
    Properties:
      DeploymentId: !Ref ServerlessRestApiDeployment
      RestApiId: !Ref ServerlessRestApi
      StageName: Prod
  SurveySubmitRole:
    Type: AWS::IAM::Role
    Properties:
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - !If
          - InternalDynamo
          - PolicyName: SurveySubmitRolePolicy
            PolicyDocument:
              Statement:
                - Action: ["dynamodb:PutItem"]
                  Resource: [!GetAtt SurveyTable.Arn]
                  Effect: Allow
          - PolicyName: SurveySubmitRolePolicy
            PolicyDocument:
              Statement:
                - Action: ["sts:AssumeRole"]
                  Resource: "*"
                  Effect: Allow
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Action:
              - sts:AssumeRole
            Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
  SurveySubmit:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: !GetAtt CopyZips.Outputs.LambdaZipsBucket
        S3Key: !Sub "${S3KeyPrefix}lambda_functions/packages/SurveySubmit/lambda.zip"
      Tags:
        - Value: SAM
          Key: lambda:createdBy
      Environment:
        Variables:
          TABLE_ARN: !If [InternalDynamo, !GetAtt SurveyTable.Arn, !Ref DynamoDbArn]
      Handler: survey_submit.lambda_handler
      Role: !GetAtt SurveySubmitRole.Arn
      Runtime: python3.7
  Survey:
    Type: AWS::Lambda::Function
    Properties:
      Handler: survey.lambda_handler
      Code:
        S3Bucket: !GetAtt CopyZips.Outputs.LambdaZipsBucket
        S3Key: !Sub "${S3KeyPrefix}lambda_functions/packages/Survey/lambda.zip"
      Role: !GetAtt SurveyRole.Arn
      Runtime: python3.7
      Tags:
        - Value: SAM
          Key: lambda:createdBy
  SurveyRestAPIPermissionProd:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:invokeFunction
      Principal: apigateway.amazonaws.com
      FunctionName: !Ref Survey
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ServerlessRestApi}/*/*/newsurvey"
  SurveyTable:
    Condition: InternalDynamo
    Type: AWS::DynamoDB::Table
    Properties:
      ProvisionedThroughput:
        WriteCapacityUnits: 5
        ReadCapacityUnits: 5
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      KeySchema:
        - KeyType: HASH
          AttributeName: id
  ServerlessRestApiDeployment:
    Type: AWS::ApiGateway::Deployment
    Properties:
      RestApiId: !Ref ServerlessRestApi
      Description: "Survey App deployment"
      StageName: Stage
  ServerlessRestApi:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Body:
        info:
          version: "1.0"
          title: !Ref AWS::StackName
        paths:
          /submitsurvey:
            x-amazon-apigateway-any-method:
              x-amazon-apigateway-integration:
                httpMethod: POST
                type: aws_proxy
                uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${SurveySubmit.Arn}/invocations"
              responses: {}
          /newsurvey:
            x-amazon-apigateway-any-method:
              x-amazon-apigateway-integration:
                httpMethod: POST
                type: aws_proxy
                uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Survey.Arn}/invocations"
              responses: {}
        swagger: "2.0"
  SurveySubmitRestAPIPermissionProd:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:invokeFunction
      Principal: apigateway.amazonaws.com
      FunctionName: !Ref SurveySubmit
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ServerlessRestApi}/*/*/submitsurvey"
Outputs:
  SurveyURL:
    Description: Link to your Serverless Survey
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/newsurvey"