AWSTemplateFormatVersion: '2010-09-09'
Description: >-
  Account-neutral EG334S active eu-west-1b application target for the school
  AWS account. This permission-compatible stack creates no IAM role, Lambda,
  Route 53 zone, VGW, customer gateway or VPN connection. It supplies the
  second healthy ALB target required for the active-active application tier.

Parameters:
  RecoverySubnetId:
    Type: AWS::EC2::Subnet::Id
    Description: Second-AZ public subnet output by hub-alb-eu-west-1.yaml.
  HubSecurityGroupId: { Type: 'AWS::EC2::SecurityGroup::Id' }
  KeyPairName: { Type: 'AWS::EC2::KeyPair::KeyName' }
  AlbTargetGroupArn:
    Type: String
    Description: Target group used by the Ireland Application Load Balancer.
  MonitoringTopicArn: { Type: String }
  InstanceType:
    Type: String
    Default: t3.micro
    AllowedValues: [t3.micro, t3.small]
  LatestAmiId:
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64

Resources:
  SecondaryLaunchTemplate:
    Type: AWS::EC2::LaunchTemplate
    Properties:
      LaunchTemplateName: !Sub '${AWS::StackName}-launch-template'
      LaunchTemplateData:
        ImageId: !Ref LatestAmiId
        InstanceType: !Ref InstanceType
        KeyName: !Ref KeyPairName
        MetadataOptions: { HttpTokens: required, HttpEndpoint: enabled }
        Monitoring: { Enabled: false }
        NetworkInterfaces:
          - DeviceIndex: 0
            AssociatePublicIpAddress: true
            Groups: [!Ref HubSecurityGroupId]
            DeleteOnTermination: true
        BlockDeviceMappings:
          - DeviceName: /dev/xvda
            Ebs:
              VolumeSize: 8
              VolumeType: gp3
              Encrypted: true
              DeleteOnTermination: true
        UserData:
          Fn::Base64: !Sub |
            #!/bin/bash
            set -euxo pipefail
            dnf install -y httpd
            mkdir -p /etc/systemd/system/httpd.service.d
            cat > /etc/systemd/system/httpd.service.d/eg334s.conf <<'EOF'
            [Service]
            Restart=always
            RestartSec=3
            EOF
            TOKEN=$(curl -fsS -X PUT -H 'X-aws-ec2-metadata-token-ttl-seconds: 21600' http://169.254.169.254/latest/api/token)
            INSTANCE_ID=$(curl -fsS -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id)
            PRIVATE_IP=$(curl -fsS -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/local-ipv4)
            cat > /var/www/html/index.html <<EOF
            <!doctype html><meta charset="utf-8">
            <title>EG334S · active secondary AWS hub</title>
            <body style="font:16px/1.6 system-ui;margin:40px">
            <h1>EG334S · AWS application hub</h1>
            <p>This response is served by the active eu-west-1b application target.</p>
            <ul><li>Region: eu-west-1 (Europe - Ireland)</li>
            <li>Availability Zone: eu-west-1b</li>
            <li>VPC CIDR: 10.1.0.0/16</li>
            <li>Instance: $INSTANCE_ID</li><li>Private IP: $PRIVATE_IP</li></ul>
            </body>
            EOF
            printf 'ok\n' > /var/www/html/health
            systemctl daemon-reload
            systemctl enable --now httpd
        TagSpecifications:
          - ResourceType: instance
            Tags:
              - { Key: Name, Value: eg334s-team2-awspublic-server-secondary }
              - { Key: Project, Value: EG334S }
              - { Key: Purpose, Value: ActiveSecondary }
          - ResourceType: volume
            Tags:
              - { Key: Name, Value: eg334s-team2-hub-secondary-volume }
              - { Key: Project, Value: EG334S }

  SecondaryAutoScalingGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      AutoScalingGroupName: !Sub '${AWS::StackName}-ActiveSecondaryAsg'
      MinSize: '1'
      DesiredCapacity: '1'
      MaxSize: '1'
      HealthCheckType: ELB
      HealthCheckGracePeriod: 300
      VPCZoneIdentifier: [!Ref RecoverySubnetId]
      TargetGroupARNs: [!Ref AlbTargetGroupArn]
      MetricsCollection:
        - Granularity: 1Minute
          Metrics:
            - GroupInServiceInstances
      LaunchTemplate:
        LaunchTemplateId: !Ref SecondaryLaunchTemplate
        Version: !GetAtt SecondaryLaunchTemplate.LatestVersionNumber
      Tags:
        - { Key: Project, Value: EG334S, PropagateAtLaunch: true }
        - { Key: Purpose, Value: ActiveSecondary, PropagateAtLaunch: true }

  SecondaryCapacityAlarm:
    Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmName: eg334s-team2-Hub-Secondary-Capacity-Low
      AlarmDescription: Active eu-west-1b ALB target capacity dropped below one.
      Namespace: AWS/AutoScaling
      MetricName: GroupInServiceInstances
      Dimensions:
        - Name: AutoScalingGroupName
          Value: !Ref SecondaryAutoScalingGroup
      Statistic: Minimum
      Period: 60
      EvaluationPeriods: 2
      DatapointsToAlarm: 2
      Threshold: 1
      ComparisonOperator: LessThanThreshold
      TreatMissingData: breaching
      AlarmActions: [!Ref MonitoringTopicArn]
      OKActions: [!Ref MonitoringTopicArn]

Outputs:
  SecondaryAutoScalingGroupName: { Value: !Ref SecondaryAutoScalingGroup }
  SecondarySubnetId: { Value: !Ref RecoverySubnetId }
  OperatingModel: { Value: ACTIVE-ACTIVE-ALB-NO-CUSTOM-IAM }
