# 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

name: Cleanup Image Tags

on:
  schedule:
    - cron: '0 0 * * SAT'
  delete:
  pull_request:
    types:
      - closed
  push:
    paths:
      - ".github/workflows/cleanup-tags.yml"
      - ".github/scripts/cleanup-tags.py"
      - ".github/scripts/common.py"

jobs:
  cleanup:
    name: Cleanup Image Tags
    runs-on: ubuntu-20.04
    env:
      # Requires a personal access token with the OAuth scope delete:packages
      TOKEN: ${{ secrets.GHA_CONTAINER_DELETE_TOKEN }}
    steps:
      -
        name: Checkout
        uses: actions/checkout@v3
      -
        name: Login to Github Container Registry
        uses: docker/login-action@v1
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      -
        name: Set up Python
        uses: actions/setup-python@v3
        with:
          python-version: "3.10"
      -
        name: Install requests
        run: |
          python -m pip install requests
      -
        name: Cleanup feature tags
        # Only run if the token is not empty
        if: "${{ env.TOKEN != '' }}"
        run: |
          python ${GITHUB_WORKSPACE}/.github/scripts/cleanup-tags.py --loglevel info --untagged --delete
      -
        name: Check all tags still pull
        run: |
          ghcr_name=$(echo "${GITHUB_REPOSITORY}" | awk '{ print tolower($0) }')
          docker pull --quiet --all-tags ghcr.io/${ghcr_name}
