---
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Deploy Caddy App'
Parameters:
  EipAllocId:
    Description: 'The EIP ID to be associated with the Caddy app instance'
    Type: 'String'
  ProjectName:
    Description: 'The value for the Name tag associated with the EC2 instance'
    Type: 'String'
  VpcId:
    Description: 'Existing VPC ID that will host the Caddy app'
    Type: 'AWS::EC2::VPC::Id'
  SubnetId:
    Description: 'ID of an existing subnet within the specified VPC'
    Type: 'AWS::EC2::Subnet::Id'
  AmiId:
    Description: 'AMI ID to use for the Caddy app'
    Type: 'AWS::EC2::Image::Id'
  DeploymentVolumeId:
    Description: 'Volume ID for the Caddy deployment volume'
    Type: 'AWS::EC2::Volume::Id'
  DataVolumeId:
    Description: 'Volume ID for the Caddy data volume'
    Type: 'AWS::EC2::Volume::Id'
  SecurityGroupId:
    Description: 'Security Group ID for the Caddy instance'
    Type: 'AWS::EC2::SecurityGroup::Id'
Resources:
  IamInstanceProfile:
    Type: 'AWS::IAM::InstanceProfile'
    Properties:
      Roles:
        - CloudWatchLogger
  CaddyENI:
    Type: 'AWS::EC2::NetworkInterface'
    Properties:
      SubnetId: !Ref SubnetId
      GroupSet:
        - !Ref SecurityGroupId
      Tags:
        - Key: Name
          Value: !Sub "${ProjectName}-ENI"
        - Key: repo
          Value: !Ref ProjectName
  CaddyInstance:
    Type: 'AWS::EC2::Instance'
    DependsOn: CaddyENI
    Properties:
      ImageId: !Ref AmiId
      InstanceType: 't3.micro'
      IamInstanceProfile: !Ref IamInstanceProfile
      NetworkInterfaces:
        - DeviceIndex: 0
          NetworkInterfaceId: !Ref CaddyENI
          DeleteOnTermination: false
      Tags:
        - Key: Name
          Value: !Ref ProjectName
        - Key: repo
          Value: !Ref ProjectName
  DeploymentVolumeAttachment:
    Type: AWS::EC2::VolumeAttachment
    DependsOn: CaddyInstance
    Properties:
      InstanceId: !Ref CaddyInstance
      VolumeId: !Ref DeploymentVolumeId
      Device: /dev/sdf
  DataVolumeAttachment:
    Type: AWS::EC2::VolumeAttachment
    DependsOn: CaddyInstance
    Properties:
      InstanceId: !Ref CaddyInstance
      VolumeId: !Ref DataVolumeId
      Device: /dev/sdg
  CaddyInstanceEipAssociation:
    Type: AWS::EC2::EIPAssociation
    DependsOn: CaddyENI
    Properties:
      AllocationId: !Ref EipAllocId
      NetworkInterfaceId: !Ref CaddyENI