name: Delete Public ECR Image
on:
  workflow_dispatch:
  pull_request:
    types: ['unlabeled', 'closed']
jobs:
  remove:
    if: ${{ github.event.label.name == 'status/image_testing' || ( github.event.action == 'closed' && (contains(github.event.pull_request.labels, 'status/image_testing'))) }}
    runs-on: ubuntu-latest
    steps:
      - name: get branch name
        id: extract_branch
        run: |
          echo
          tag='${{ github.event.pull_request.number }}'
          echo "tag=${tag}" >> $GITHUB_OUTPUT
      - name: Configure AWS credentials for Kafka-UI account
        uses: aws-actions/configure-aws-credentials@v2
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-east-1
      - name: Login to Amazon ECR
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@v1
        with:
          registry-type: 'public'
      - name: Remove from ECR
        id: remove_from_ecr
        run: |
          aws ecr-public batch-delete-image \
                --repository-name kafka-ui-custom-build \
                --image-ids imageTag=${{ steps.extract_branch.outputs.tag }} \
                --region us-east-1
      - name: make comment with private deployment link
        uses: peter-evans/create-or-update-comment@v2
        with:
          issue-number: ${{ github.event.pull_request.number }}
          body: |
            Image tag public.ecr.aws/provectus/kafka-ui-custom-build:${{ steps.extract_branch.outputs.tag }} has been removed
