# This workflow runs on certain conditions to check for and potentially
# delete container images from the GHCR which no longer have an associated
# code branch.
# Requires a PAT with the correct scope set in the secrets.
#
# This workflow will not trigger runs on forked repos.

name: Cleanup Image Tags
on:
  delete:
  push:
    paths:
      - ".github/workflows/cleanup-tags.yml"
concurrency:
  group: registry-tags-cleanup
  cancel-in-progress: false
jobs:
  cleanup-images:
    name: Cleanup Image Tags for ${{ matrix.primary-name }}
    if: github.repository_owner == 'paperless-ngx'
    runs-on: ubuntu-24.04
    strategy:
      fail-fast: false
      matrix:
        primary-name: ["paperless-ngx", "paperless-ngx/builder/cache/app"]
    env:
      # Requires a personal access token with the OAuth scope delete:packages
      TOKEN: ${{ secrets.GHA_CONTAINER_DELETE_TOKEN }}
    steps:
      - name: Clean temporary images
        if: "${{ env.TOKEN != '' }}"
        uses: stumpylog/image-cleaner-action/ephemeral@v0.10.0
        with:
          token: "${{ env.TOKEN }}"
          owner: "${{ github.repository_owner }}"
          is_org: "true"
          package_name: "${{ matrix.primary-name }}"
          scheme: "branch"
          repo_name: "paperless-ngx"
          match_regex: "(feature|fix)"
          do_delete: "true"
  cleanup-untagged-images:
    name: Cleanup Untagged Images Tags for ${{ matrix.primary-name }}
    if: github.repository_owner == 'paperless-ngx'
    runs-on: ubuntu-24.04
    needs:
      - cleanup-images
    strategy:
      fail-fast: false
      matrix:
        primary-name: ["paperless-ngx", "paperless-ngx/builder/cache/app"]
    env:
      # Requires a personal access token with the OAuth scope delete:packages
      TOKEN: ${{ secrets.GHA_CONTAINER_DELETE_TOKEN }}
    steps:
      - name: Clean untagged images
        if: "${{ env.TOKEN != '' }}"
        uses: stumpylog/image-cleaner-action/untagged@v0.10.0
        with:
          token: "${{ env.TOKEN }}"
          owner: "${{ github.repository_owner }}"
          is_org: "true"
          package_name: "${{ matrix.primary-name }}"
          do_delete: "true"
