# 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 paperless-ngx
    if: github.repository_owner == 'paperless-ngx'
    runs-on: ubuntu-22.04
    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.1.0
        with:
          token: "${{ env.TOKEN }}"
          owner: "${{ github.repository_owner }}"
          is_org: "true"
          package_name: "paperless-ngx"
          scheme: "branch"
          repo_name: "paperless-ngx"
          match_regex: "feature-"
          do_delete: "true"

  cleanup-untagged-images:
    name: Cleanup Untagged Images Tags for ${{ matrix.primary-name }}
    if: github.repository_owner == 'paperless-ngx'
    runs-on: ubuntu-22.04
    needs:
      - cleanup-images
    strategy:
      fail-fast: false
      matrix:
        include:
          - primary-name: "paperless-ngx"
          - primary-name: "paperless-ngx/builder/cache/app"
          # TODO: Remove the above and replace with the below
          # - primary-name: "builder/qpdf"
          # - primary-name: "builder/cache/qpdf"
          # - primary-name: "builder/pikepdf"
          # - primary-name: "builder/cache/pikepdf"
          # - primary-name: "builder/jbig2enc"
          # - primary-name: "builder/cache/jbig2enc"
          # - primary-name: "builder/psycopg2"
          # - primary-name: "builder/cache/psycopg2"
    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.1.0
        with:
          token: "${{ env.TOKEN }}"
          owner: "${{ github.repository_owner }}"
          is_org: "true"
          package_name: "${{ matrix.primary-name }}"
          do_delete: "true"
