---
AWSTemplateFormatVersion: '2010-09-09'


Description: 'CodeBuild noids from GitHub to S3 using hesburghlibraries/noids-buildimage'


Metadata:

  AWS::CloudFormation::Interface:
    ParameterLabels:
      CodeBuildRole: {default: CodeBuild Role}
      TargetBucket: {default: Artifact Target S3 Bucket}
      LogRetention: {default: Build Log Retention}
    ParameterGroups:
      - Label: {default: CodeBuild Settings}
        Parameters:
          - CodeBuildRole
          - TargetBucket
          - LogRetention


Outputs:

  BuildLogsURL:
    Value: !Sub https://console.aws.amazon.com/cloudwatch/home?region=${AWS::Region}#logStream:group=${LogGroup}

  CodeBuildURL:
    Value: !Sub https://console.aws.amazon.com/codebuild/home?region=${AWS::Region}#/projects/${Project}/view

  RepoURL:
    Value: https://github.com/ndlib/noids.git


Parameters:

  CodeBuildRole:
    Type: String
    Description: IAM role
    Default: ''

  TargetBucket:
    Type: String
    Description: S3 bucket name
    Default: ''

  LogRetention:
    Type: Number
    Description: days
    Default: 400
    AllowedValues: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]


Conditions:

  NoBucket: !Equals ['', !Ref TargetBucket]
  NoCodeBuildRole: !Equals ['', !Ref CodeBuildRole]


Resources:

  Bucket:
    Condition: NoBucket
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: PublicRead

  BucketPolicy:
    Condition: NoBucket
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref Bucket
      PolicyDocument:
        Version: 2012-10-17
        Id: PublicRead
        Statement:
        - Sid: PublicReadForGetBucketObjects
          Effect: Allow
          Principal: '*'
          Action: 's3:GetObject'
          Resource:
          - !GetAtt Bucket.Arn
          - !Sub '${Bucket.Arn}/*'

  LogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Sub /aws/codebuild/${Project}
      RetentionInDays: !Ref LogRetention

  GitHubWebhook:
    Type: Custom::GitHubWebhook
    Version: '1.0'
    Properties:
      ServiceToken: !ImportValue Custom::GitHubWebhook
      Name: !Ref Project

  Project:
    Type: AWS::CodeBuild::Project
    Properties:
      Name: noids
      Description: 'noids from GitHub to S3 rpm'
      ServiceRole: !If [NoCodeBuildRole, !ImportValue 'codebuild:role', !Ref CodeBuildRole]
      TimeoutInMinutes: 5
      Source: {Type: GITHUB, Location: 'https://github.com/ndlib/noids.git'}
      Artifacts:
        Type: S3
        Packaging: NONE
        NamespaceType: NONE
        Path: noids
        Name: rpms
        Location: !If [NoBucket, !Ref Bucket, !Ref TargetBucket]
      Environment:
        Type: LINUX_CONTAINER
        ComputeType: BUILD_GENERAL1_SMALL
        Image: hesburghlibraries/noids-buildimage
...
