name: WebhookListenerAutodCleanup

on:
  delete:
    branches:
    - autod-feature/*

jobs:
  ShouldRunCleanup:
    runs-on: ubuntu-latest
    outputs:
      is_autod_branch: ${{ steps.IsAutod.outputs.is_autod_branch }}
    steps:
    - name: IsAutod
      id: IsAutod
      run: |
        is_autod='false'
        if [[ ${{ github.event.ref }} =~ "autod-feature/" ]]; then
          is_autod='true'
        fi
        echo "::set-output name=is_autod_branch::$is_autod"
  
  DeleteAllRelatedContainers:
    runs-on: ubuntu-latest
    env:
      FULL_IMAGE_NAME: gcr.io/arborknot-dev/webhook-listener
      PROJECT_ID: arborknot-dev
    permissions:
      id-token: 'write'
      contents: 'read'
    needs: ShouldRunCleanup
    if: needs.ShouldRunCleanup.outputs.is_autod_branch == 'true'
    steps:
    - name: Update Image Name
      run: |
        FULL_BRANCH_NAME=${{ github.event.ref }}
        echo "FULL_IMAGE_NAME=${{ env.FULL_IMAGE_NAME }}-${FULL_BRANCH_NAME#*/}" >> $GITHUB_ENV
    - uses: actions/checkout@v3
    - id: 'auth'
      name: 'Authenticate to Google Cloud'
      uses: 'google-github-actions/auth@v0.7.0'
      with:
        workload_identity_provider: '${{ secrets.GCP_DEV_WORKLOAD_IDENTITY_ID }}'
        service_account: '${{ secrets.GCP_DEV_SERVICE_ACCOUNT }}'
    - name: Delete all related images
      run: |
        images=$(gcloud container images list-tags ${{ env.FULL_IMAGE_NAME }} --format="get(digest)") 
        for image in ${images[@]}; do 
          gcloud container images delete ${{ env.FULL_IMAGE_NAME }}@${image} --quiet --force-delete-tags
        done

  TriggerAKDevopsAutodCleanup:
    runs-on: ubuntu-latest
    needs: ShouldRunCleanup
    if: needs.ShouldRunCleanup.outputs.is_autod_branch == 'true'
    steps:
    - name: Trigger Autod Cleanup Workflow
      uses: benc-uk/workflow-dispatch@v1
      with: 
        workflow: AutodCleanupWorkflow
        token: ${{ secrets.DEV_ENV_PIPELINE_TOKEN }}
        inputs: '{ "branch": "${{ github.event.ref }}" }'
        repo: "Arborknot/AK-Devops"
        ref: "main"
