name: Update Flake

on:
  workflow_dispatch: # allows manual triggering
  schedule:
    - cron: '33 3 * * 6' # runs weekly on Saturday at 03:33

permissions:
  contents: write
  pull-requests: write
  checks: write

jobs:
  lockfile:
    name: Lockfile
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v3
      - name: Install Nix
        uses: DeterminateSystems/nix-installer-action@v11
        with:
          nix-package-url: https://releases.nixos.org/nix/nix-2.18.4/nix-2.18.4-x86_64-linux.tar.xz
      - name: Check Nixpkgs Inputs
        uses: DeterminateSystems/flake-checker-action@v7
      - name: Add Nix Cache
        uses: DeterminateSystems/magic-nix-cache-action@v6
      - name: Update flake.lock
        uses: DeterminateSystems/update-flake-lock@v23
        id: update
        with:
          pr-title: "Update flake.lock" # Title of PR to be created
          pr-labels: |                  # Labels to be set on the PR
            dependencies
            automated
          pr-body: |
            Automated changes by the [update-flake-lock](https://github.com/DeterminateSystems/update-flake-lock) GitHub Action.

            ```
            {{ env.GIT_COMMIT_MESSAGE }}
            ```
      - name: Check the Flake
        id: check
        run: nix flake check
      - name: Update Check Status
        uses: LouisBrunner/checks-action@v1.6.1
        if: always()
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          name: Update Flake
          conclusion: ${{ job.status }}
          output: |
            {"summary":"${{ steps.check.outputs.stdout }}"}
      - name: Enable Pull Request Automerge
        if: success()
        run: |
          gh pr merge \
            --rebase \
            --auto \
            ${{ steps.update.outputs.pull-request-number }}
        env:
          GH_TOKEN: ${{ github.token }}
      - name: Close Pull Request If Failed
        if: failure()
        run: |
          gh pr close \
            --comment "Auto-closing pull request" \
            --delete-branch \
            ${{ steps.update.outputs.pull-request-number }}
        env:
          GH_TOKEN: ${{ github.token }}