AWSTemplateFormatVersion: 2010-09-09
Description: >-
  AWS CloudFormation template for the Homegrown Spotify assignment DP1.
Parameters:

  UvaId:
    Description: UVA Computing ID
    Type: String
    MinLength: 3
    MaxLength: 8
    ConstraintDescription: must be between 3 and 8 characters

  KeyName:
    Description: Select an existing EC2 KeyPair to enable SSH access to your instance
    Type: 'AWS::EC2::KeyPair::KeyName'
    ConstraintDescription: must be the name of an existing EC2 KeyPair.

Resources:

  StaticWebHostBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub "${UvaId}-dp1-spotify"
      OwnershipControls:
        Rules:
          - ObjectOwnership: BucketOwnerEnforced
      PublicAccessBlockConfiguration:
        BlockPublicAcls: false
        BlockPublicPolicy: false
        IgnorePublicAcls: false
        RestrictPublicBuckets: false
      WebsiteConfiguration:
        IndexDocument: index.html
        ErrorDocument: error.html

  StaticWebHostBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      Bucket: !Ref StaticWebHostBucket
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Sid: PublicReadForGetBucketObjects
            Effect: Allow
            Principal: '*'
            Action: 's3:GetObject'
            Resource: !Join 
              - ''
              - - 'arn:aws:s3:::'
                - !Ref StaticWebHostBucket
                - /*
          - Sid: PutObjectAccessForInstructors
            Action:
              - s3:PutObject
            Effect: Allow
            Principal:
              AWS:
                - '440848399208'
            Resource:
              - !Sub "arn:aws:s3:::${StaticWebHostBucket}"
              - !Sub "arn:aws:s3:::${StaticWebHostBucket}/*"

  EC2Instance:
    Type: 'AWS::EC2::Instance'
    Properties:
      InstanceType: t2.micro
      SecurityGroups:
        - !Ref InstanceSecurityGroup
      KeyName: !Ref KeyName
      ImageId: ami-0cc99c9f52e86139d
      Tags:
        - Key: Name
          Value: dp1-spotify

  InstanceSecurityGroup:
    Type: 'AWS::EC2::SecurityGroup'
    Properties:
      GroupDescription: Enable SSH access
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: '22'
          ToPort: '22'
          CidrIp: '0.0.0.0/0'
        - IpProtocol: tcp
          FromPort: '80'
          ToPort: '80'
          CidrIp: '0.0.0.0/0'
          
  IPAddress:
    Type: 'AWS::EC2::EIP'

  IPAssoc:
    Type: 'AWS::EC2::EIPAssociation'
    Properties:
      InstanceId: !Ref EC2Instance
      EIP: !Ref IPAddress

Outputs:
  EC2InstanceIPAddress:
    Description: IP address of the newly created EC2 instance
    Value: !Ref IPAddress
  S3Bucket:
    Value: !Ref StaticWebHostBucket
    Description: S3 Bucket for DP1 storage
  S3WebsiteURL:
    Value: !GetAtt 
      - StaticWebHostBucket
      - WebsiteURL
    Description: DP1 Spotify application URL