name: Cleanup ephemeral envs (PR close)

on:
  pull_request_target:
    types: [closed]

jobs:
  config:
    runs-on: "ubuntu-22.04"
    outputs:
      has-secrets: ${{ steps.check.outputs.has-secrets }}
    steps:
      - name: "Check for secrets"
        id: check
        shell: bash
        run: |
          if [ -n "${{ (secrets.AWS_ACCESS_KEY_ID != '' && secrets.AWS_SECRET_ACCESS_KEY != '') || '' }}" ]; then
            echo "has-secrets=1" >> "$GITHUB_OUTPUT"
          fi

  ephemeral-env-cleanup:
    needs: config
    if: needs.config.outputs.has-secrets
    name: Cleanup ephemeral envs
    runs-on: ubuntu-22.04
    permissions:
      pull-requests: write
    steps:
      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-west-2

      - name: Describe ECS service
        id: describe-services
        run: |
          echo "active=$(aws ecs describe-services --cluster superset-ci --services pr-${{ github.event.number }}-service | jq '.services[] | select(.status == "ACTIVE") | any')" >> $GITHUB_OUTPUT

      - name: Delete ECS service
        if: steps.describe-services.outputs.active == 'true'
        id: delete-service
        run: |
          aws ecs delete-service \
          --cluster superset-ci \
          --service pr-${{ github.event.number }}-service \
          --force

      - name: Login to Amazon ECR
        if: steps.describe-services.outputs.active == 'true'
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@v2

      - name: Delete ECR image tag
        if: steps.describe-services.outputs.active == 'true'
        id: delete-image-tag
        run: |
          aws ecr batch-delete-image \
          --registry-id $(echo "${{ steps.login-ecr.outputs.registry }}" | grep -Eo "^[0-9]+") \
          --repository-name superset-ci \
          --image-ids imageTag=pr-${{ github.event.number }}

      - name: Comment (success)
        if: steps.describe-services.outputs.active == 'true'
        uses: actions/github-script@v7
        with:
          github-token: ${{github.token}}
          script: |
            github.rest.issues.createComment({
              issue_number: ${{ github.event.number }},
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: 'Ephemeral environment shutdown and build artifacts deleted.'
            })
