---
AWSTemplateFormatVersion: 2010-09-09

Parameters:
    InstanceType:
        Type: String

    Ami:
        Type: String

    SnapshotId:
        Type: String

    AvailabilityZone:
        Type: String

    S3Bucket:
        Type: String

    PerfTestId:
        Type: String

    SnsTopic:
        Type: String

    SqsArn:
        Type: String

    SqsUrl:
        Type: String

    MaxPrice:
        Type: String

    FleetSize:
        Type: String

    SSHKeyName:
        Type: String

    WitnessCheck:
        Type: String

    CompareTo:
        Type: String

Conditions:
    UseSpot: !Not [!Equals [!Ref MaxPrice, ""]]

    UseKey: !Not [!Equals [!Ref SSHKeyName, ""]]

Resources:
    EC2Role:
        Type: "AWS::IAM::Role"
        Properties:
            AssumeRolePolicyDocument:
                Version: 2012-10-17
                Statement:
                    Effect: Allow
                    Principal:
                        Service: ec2.amazonaws.com
                    Action: "sts:AssumeRole"
            RoleName: !Sub "ER-${PerfTestId}"
            Policies:
                - PolicyName: !Sub "EP-${PerfTestId}"
                  PolicyDocument:
                    Version: 2012-10-17
                    Statement:
                        - Action:
                            - "s3:PutObject"
                            - "s3:GetObject"
                          Effect: Allow
                          Resource: !Join ["/", [!Sub "arn:aws:s3:::${S3Bucket}", "*"]]
                        - Action:
                            - "s3:ListBucket"
                          Effect: Allow
                          Resource: !Sub "arn:aws:s3:::${S3Bucket}"
                        - Action:
                            - "sns:Publish"
                          Effect: Allow
                          Resource: !Ref SnsTopic
                        - Action:
                            - "sqs:DeleteMessage"
                            - "sqs:DeleteQueue"
                            - "sqs:GetQueueAttributes"
                            - "sqs:ReceiveMessage"
                          Effect: Allow
                          Resource: !Ref SqsArn
                        - Action:
                            - "sqs:DeleteMessage"
                            - "sqs:DeleteQueue"
                            - "sqs:GetQueueAttributes"
                            - "sqs:ReceiveMessage"
                            - "sqs:SendMessage"
                          Effect: Allow
                          Resource: !Sub "${SqsArn}-run"
                        - Action:
                            - "cloudformation:DeleteStack"
                          Effect: Allow
                          Resource: !Sub "arn:aws:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/perf-test-*/*"
                        - Action:
                            - "autoscaling:DeleteAutoScalingGroup"
                            - "autoscaling:DeleteLaunchConfiguration"
                            - "autoscaling:DescribeAutoScalingGroups"
                            - "autoscaling:DescribeScalingActivities"
                            - "autoscaling:UpdateAutoScalingGroup"
                            - "ec2:DeleteSecurityGroup"
                            - "iam:DeleteInstanceProfile"
                            - "iam:DeleteRole"
                            - "iam:DeleteRolePolicy"
                            - "iam:RemoveRoleFromInstanceProfile"
                          Effect: Allow
                          Resource: "*"

    EC2InstanceProfile:
        Type: "AWS::IAM::InstanceProfile"
        Properties:
            Roles:
                - !Ref EC2Role

    SecurityGroupInSSHWorld:
        Type: "AWS::EC2::SecurityGroup"
        DependsOn: EC2Role
        Properties:
            GroupDescription: SSH access
            SecurityGroupIngress:
                - IpProtocol: tcp
                  FromPort: 22
                  ToPort: 22
                  CidrIp: '0.0.0.0/0'

    LaunchConfiguration:
        Type: "AWS::AutoScaling::LaunchConfiguration"
        Properties:
            BlockDeviceMappings:
                - DeviceName: "/dev/sdf"
                  Ebs:
                      DeleteOnTermination: True
                      SnapshotId: !Ref SnapshotId
                      VolumeSize: 64
            IamInstanceProfile: !Ref EC2InstanceProfile
            ImageId: !Ref Ami
            InstanceType: !Ref InstanceType
            KeyName:
                !If [UseKey, !Ref SSHKeyName, !Ref "AWS::NoValue"]
            SecurityGroups:
                - !Ref SecurityGroupInSSHWorld
            SpotPrice:
                !If [UseSpot, !Ref MaxPrice, !Ref "AWS::NoValue"]
            UserData:
                Fn::Base64: !Sub |
                    #!/bin/bash
                    set -x -e

                    # install awscli
                    apt-get -y update
                    apt-get install -y awscli

                    # AWS Sig-v4 access
                    aws configure set s3.signature_version s3v4

                    aws s3 cp s3://${S3Bucket}/ec2-terminate.sh /etc/init.d/ec2-terminate
                    sed -i 's/#SNSTOPIC#/${SnsTopic}/g' /etc/init.d/ec2-terminate
                    sed -i 's/#MAXPRICE#/${MaxPrice}/g' /etc/init.d/ec2-terminate
                    sed -i 's/#S3BUCKET#/${S3Bucket}/g' /etc/init.d/ec2-terminate
                    sed -i 's/#PERFTESTID#/${PerfTestId}/g' /etc/init.d/ec2-terminate
                    chmod a+x /etc/init.d/ec2-terminate
                    update-rc.d ec2-terminate defaults
                    systemctl start ec2-terminate

                    aws s3 cp s3://${S3Bucket}/run-on-ec2.sh /root/run-on-ec2.sh
                    sed -i 's#:WITNESSCHECK:#${WitnessCheck}#g' /root/run-on-ec2.sh
                    sed -i 's#:AWSREGION:#${AWS::Region}#g' /root/run-on-ec2.sh
                    sed -i 's#:SNSTOPIC:#${SnsTopic}#g' /root/run-on-ec2.sh
                    sed -i 's#:SQSURL:#${SqsUrl}#g' /root/run-on-ec2.sh
                    sed -i 's#:S3BUCKET:#${S3Bucket}#g' /root/run-on-ec2.sh
                    sed -i 's#:PERFTESTID:#${PerfTestId}#g' /root/run-on-ec2.sh
                    sed -i 's#:INSTANCETYPE:#${InstanceType}#g' /root/run-on-ec2.sh
                    sed -i 's#:COMPARETO:#${CompareTo}#g' /root/run-on-ec2.sh
                    . /root/run-on-ec2.sh

    AutoScalingGroup:
        Type: "AWS::AutoScaling::AutoScalingGroup"
        Properties:
            AvailabilityZones:
                - !Ref AvailabilityZone
            DesiredCapacity: !Ref FleetSize
            LaunchConfigurationName: !Ref LaunchConfiguration
            MaxSize: !Ref FleetSize
            MinSize: 1

Outputs:
    ASGId:
       Value: !Ref AutoScalingGroup
