---
name: Gen - Compress images

on:
  push:
    branches:
      - main
    paths:
      - "**.jpg"
      - "**.jpeg"
      - "**.png"
      - "**.webp"
  pull_request:
    paths:
      - "**.jpg"
      - "**.jpeg"
      - "**.png"
      - "**.webp"
  workflow_dispatch:

jobs:
  compress:
    name: compress
    runs-on: ubuntu-latest
    # Don't run on forks. Token will not be available. Will run on main and open a PR anyway
    if: |
      github.repository == 'goauthentik/authentik' &&
      (github.event_name != 'pull_request' ||
       github.event.pull_request.head.repo.full_name == github.repository)
    steps:
      - id: generate_token
        uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v2
        with:
          app-id: ${{ secrets.GH_APP_ID }}
          private-key: ${{ secrets.GH_APP_PRIV_KEY }}
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v5
        with:
          token: ${{ steps.generate_token.outputs.token }}
      - name: Compress images
        id: compress
        uses: calibreapp/image-actions@e2cc8db5d49c849e00844dfebf01438318e96fa2 # main
        with:
          GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
          compressOnly: ${{ github.event_name != 'pull_request' }}
      - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v7
        if: "${{ github.event_name != 'pull_request' && steps.compress.outputs.markdown != '' }}"
        id: cpr
        with:
          token: ${{ steps.generate_token.outputs.token }}
          title: "*: Auto compress images"
          branch-suffix: timestamp
          commit-message: "*: compress images"
          body: ${{ steps.compress.outputs.markdown }}
          delete-branch: true
          signoff: true
          labels: dependencies
      - uses: peter-evans/enable-pull-request-automerge@a660677d5469627102a1c1e11409dd063606628d # v3
        if: "${{ github.event_name != 'pull_request' && steps.compress.outputs.markdown != '' }}"
        with:
          token: ${{ steps.generate_token.outputs.token }}
          pull-request-number: ${{ steps.cpr.outputs.pull-request-number }}
          merge-method: squash
