name: Launch Review App
description: Launches your Review App

runs:
  using: "composite"
  steps:
    - run: |
        echo "Creating Data Access Point"

        echo "DATA_AP_ID=$( \
          aws efs create-access-point \
            --client-token $PROJECT-$PR_NUMBER-data \
            --file-system-id $FS_ID \
            --tags Key=GanderApps,Value=four_eyes \
            --root-directory "Path=/$PROJECT-$PR_NUMBER/data,CreationInfo={OwnerUid=0,OwnerGid=0,Permissions=777}" \
            --query 'AccessPointId' \
            --output text \
        )" >> $GITHUB_ENV

      shell: bash

    - run: |
        cat << TASK_DEF > ./app-task.json
        {
          "family": "$PROJECT-$PR_NUMBER",
          "networkMode": "awsvpc",
          "executionRoleArn": "$TASK_EXECUTION_ROLE_ARN",
          "containerDefinitions": [
            {
              "name": "api",
              "image": "$IMAGE_ARN",
              "portMappings": [
                {
                  "containerPort": 8080,
                  "hostPort": 8080,
                  "protocol": "tcp"
                }
              ],
              "environment": [
                {
                  "name": "PG_USER",
                  "value": "chris"
                },
                {
                  "name": "PG_PW",
                  "value": "password2"
                },
                {
                  "name": "PG_HOST",
                  "value": "localhost"
                },
                {
                  "name": "PORT",
                  "value": "8080"
                }
              ],
              "logConfiguration": {
                "logDriver": "awslogs",
                "options": {
                  "awslogs-create-group": "true",
                  "awslogs-region": "$REGION",
                  "awslogs-group": "gander-logs-$PROJECT-api",
                  "awslogs-stream-prefix": "$PROJECT"
                }
              },
              "dependsOn": [
                {
                  "containerName": "db",
                  "condition": "HEALTHY"
                }
              ],
              "memory": 256,
              "cpu": 128,
              "essential": true
            },
            {
              "name": "db",
              "image": "postgres",
              "portMappings": [
                {
                  "containerPort": 5432,
                  "hostPort": 5432
                }
              ],
              "environment": [
                {
                  "name": "POSTGRES_USER",
                  "value": "chris"
                },
                {
                  "name": "POSTGRES_PASSWORD",
                  "value": "password2"
                },
                {
                  "name": "POSTGRES_DB",
                  "value": "$DB_NAME"
                }
              ],
              "mountPoints": [
                {
                  "sourceVolume": "sql-seed",
                  "containerPath": "/docker-entrypoint-initdb.d"
                },
                {
                  "sourceVolume": "sql-data",
                  "containerPath": "/var/lib/postgresql/data"
                }
              ],
              "logConfiguration": {
                "logDriver": "awslogs",
                "options": {
                  "awslogs-create-group": "true",
                  "awslogs-region": "$REGION",
                  "awslogs-group": "gander-logs-$PROJECT-db",
                  "awslogs-stream-prefix": "$PROJECT"
                }
              },
              "healthCheck": {
                "command": ["CMD-SHELL", "pg_isready -U chris"],
                "interval": 15,
                "timeout": 6,
                "retries": 10,
                "startPeriod": 30
              },
              "cpu": 128,
              "memory": 256,
              "essential": true
            }
          ],
          "volumes": [
            {
              "name": "sql-seed",
              "efsVolumeConfiguration": {
                "fileSystemId": "$FS_ID",
                "transitEncryption": "ENABLED",
                "authorizationConfig": {
                  "accessPointId": "$SEED_AP_ID"
                }
              }
            },
            {
              "name": "sql-data",
              "efsVolumeConfiguration": {
                "fileSystemId": "$FS_ID",
                "transitEncryption": "ENABLED",
                "authorizationConfig": {
                  "accessPointId": "$DATA_AP_ID"
                }
              }
            }
          ],
          "requiresCompatibilities": ["FARGATE"],
          "cpu": "256",
          "memory": "512"
        }
        TASK_DEF
      shell: bash

    - run: |
        echo "Registering Task Definition"

        echo "APP_TASK_DEF=$(aws ecs register-task-definition \
        --family $PROJECT-$PR_NUMBER \
        --tags key=GanderApps,value=four_eyes \
        --cli-input-json file://app-task.json \
        --query 'join(`:`,taskDefinition.[family,to_string(revision)])' \
        --output text)" >> $GITHUB_ENV
      shell: bash

    - run: |
        echo "Creating Target Group"

        VPC_ID=$(aws ec2 describe-vpcs \
        --filters Name=tag:Name,Values=gander-apps \
        --query 'Vpcs[0].VpcId' \
        --output text)

        TARGET_GROUP_ARN=$(aws elbv2 create-target-group \
        --name Gander-$PROJECT-$PR_NUMBER \
        --vpc-id $VPC_ID \
        --protocol HTTP \
        --tags Key=GanderApps,Value=four_eyes \
        --port 8080 \
        --target-type ip \
        --query 'TargetGroups[0].TargetGroupArn' \
        --output text)

        echo "Creating Rule"

        ALB_ARN=$(aws elbv2 describe-load-balancers \
        --query 'LoadBalancers[?LoadBalancerName==`gander-apps`] | [0].LoadBalancerArn' \
        --output text)

        LISTENER_ARN=$(aws elbv2 describe-listeners \
        --load-balancer-arn $ALB_ARN \
        --query 'Listeners[?Port==`80`] | [0].ListenerArn' \
        --output text)

        cat << RULES >> ./rules-conditions.json
        [
          {
            "Field": "host-header",
            "Values": ["$PROJECT-$PR_NUMBER.gander.$USER_DOMAIN"]
          }
        ]
        RULES

        RULE_ARN=$(aws elbv2 create-rule \
        --listener-arn $LISTENER_ARN \
        --conditions file://./rules-conditions.json \
        --priority $PR_NUMBER \
        --tags Key=GanderApps,Value=four_eyes \
        --actions Type=forward,TargetGroupArn=$TARGET_GROUP_ARN \
        --query 'Rules[0].RuleArn' \
        --output text)

        echo "TARGET_GROUP_ARN=$TARGET_GROUP_ARN" >> $GITHUB_ENV
      shell: bash

    - run: |
        echo "Launching App Service"
        echo "APP_SERVICE=$(aws ecs create-service \
          --cluster $PROJECT \
          --service-name $PROJECT-$PR_NUMBER-$GITHUB_SHA \
          --task-definition $APP_TASK_DEF \
          --desired-count 1 \
          --tags key=GanderApps,value=four_eyes \
          --launch-type FARGATE \
          --network-configuration "awsvpcConfiguration={ \
              subnets=[$SUBNET_ID], \
              securityGroups=[$SG_ID], \
              assignPublicIp=ENABLED \
            }" \
          --load-balancers targetGroupArn=$TARGET_GROUP_ARN,containerName=api,containerPort=8080 \
          --query 'service.serviceArn' \
          --output text)" >> $GITHUB_ENV
      shell: bash
    - run: |
        echo "Waiting for app service to be stable"
        aws ecs wait services-stable \
          --cluster $PROJECT \
          --services $PROJECT-$PR_NUMBER-$GITHUB_SHA

        echo "PUBLIC_URL=$PROJECT-$PR_NUMBER.gander.$USER_DOMAIN" >> $GITHUB_ENV
      shell: bash
