name: Update lockfile

on:
  schedule:
    - cron: "30 6 * * *"
  workflow_dispatch:

jobs:
  update-lockfile:
    name: Update lockfile
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: master

      - uses: actions/create-github-app-token@v1
        id: app-token
        with:
          app-id: ${{ vars.TOKEN_ID }}
          private-key: ${{ secrets.TOKEN_PRIVATE_KEY }}

      - name: Prepare
        env:
          NVIM_TAG: stable
        run: |
          wget https://github.com/josephburnett/jd/releases/download/v1.7.1/jd-amd64-linux
          mv jd-amd64-linux /tmp/jd
          chmod +x /tmp/jd
          bash scripts/ci-install.sh

      - name: Update parsers
        env:
          SKIP_LOCKFILE_UPDATE_FOR_LANGS: "javascript"
        run: |
          cp lockfile.json /tmp/old_lockfile.json
          nvim -l scripts/write-lockfile.lua
          # Pretty print
          cp lockfile.json /tmp/lockfile.json
          cat /tmp/lockfile.json | jq --sort-keys > lockfile.json
          UPDATED_PARSERS=$(/tmp/jd -f merge /tmp/old_lockfile.json lockfile.json | jq -r 'keys | join(", ")')
          echo "UPDATED_PARSERS=$UPDATED_PARSERS" >> $GITHUB_ENV

      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v6
        with:
          token: ${{ steps.app-token.outputs.token }}
          author: "nvim-treesitter-bot[bot] <157957100+nvim-treesitter-bot[bot]@users.noreply.github.com>"
          commit-message: "bot(lockfile): update ${{ env.UPDATED_PARSERS }}"
          title: "Update lockfile.json: ${{ env.UPDATED_PARSERS }}"
          body: "[beep boop](https://github.com/peter-evans/create-pull-request)"
          branch: update-lockfile-pr
          base: ${{ github.head_ref }}

      - name: Enable Pull Request Automerge
        env:
          GH_TOKEN: ${{ steps.app-token.outputs.token }}
        run: gh pr merge --rebase --auto update-lockfile-pr
