name: Update flake.lock

on:
  push:
    branches: [master]
    paths: [go.sum]
  workflow_dispatch:

permissions:
  contents: write
  pull-requests: write

jobs:
  update:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - uses: DeterminateSystems/nix-installer-action@main

      - name: Update flake.lock
        run: nix flake update

      - name: Create Pull Request
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          git diff --quiet flake.lock && exit 0
          BRANCH="chore/update-flake-lock"
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git checkout -b "$BRANCH"
          git add flake.lock
          git commit -m "chore: update flake.lock"
          git push -f origin "$BRANCH"
          if ! gh pr list --head "$BRANCH" --state open | grep -q .; then
            gh pr create --title "chore: update flake.lock" --body "Automated flake.lock update." --base master
          fi
