name: Precompile Assets
on:
  push:
    branches:
      - master

jobs:
  precompile-assets:
    runs-on: ubuntu-latest
    permissions:
      actions: write
      contents: write
    steps:
      - name: Check out repository code
        uses: actions/checkout@v4
      - name: Set up Ruby
        uses: ruby/setup-ruby@v1
        with:
          ruby-version: ruby
          bundler-cache: true
      - name: Create .sprockets-manifest.json without mtime
        run: |
          yq 'del(.. | select(has("mtime")).mtime)' lib/gollum/public/assets/.sprockets-manifest-*.json | tee /tmp/.sprockets-manifest.json
      - name: Hash assets
        id: hash-before
        run: |
          echo "hash=${{ hashFiles('lib/gollum/public/assets/**/*', '!lib/gollum/public/assets/.sprockets-manifest-*.json', '/tmp/.sprockets-manifest.json') }}" | tee -a "$GITHUB_OUTPUT"
      - name: Precompile assets
        run: bundle exec rake precompile
      - name: Create .sprockets-manifest.json without mtime
        run: |
          yq 'del(.. | select(has("mtime")).mtime)' lib/gollum/public/assets/.sprockets-manifest-*.json | tee /tmp/.sprockets-manifest.json
      - name: Hash assets
        id: hash-after
        run: |
          echo "hash=${{ hashFiles('lib/gollum/public/assets/**/*', '!lib/gollum/public/assets/.sprockets-manifest-*.json', '/tmp/.sprockets-manifest.json') }}" | tee -a "$GITHUB_OUTPUT"
      - name: Commit
        if: steps.hash-before.outputs.hash != steps.hash-after.outputs.hash
        run: |
          git config user.email 41898282+github-actions[bot]@users.noreply.github.com
          git config user.name github-actions[bot]
          git add -A lib/gollum/public/assets
          git commit -m 'Precompile assets'
          git push
          # Pushing with the implict token won't trigger another workflow,
          # so manually trigger the workflow with github cli instead.
          gh workflow run docker-deploy.yml --repo ${{ github.repository }}
        env:
          GH_TOKEN: ${{ github.token }}
