name: Sync gomod2nix.toml

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

permissions:
  contents: write
  pull-requests: write

jobs:
  sync:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6

      - name: Install Nix
        uses: cachix/install-nix-action@ab739621df7a23f52766f9ccc97f38da6b7af14f # v31
        with:
          nix_path: nixpkgs=channel:nixpkgs-unstable

      - name: Generate gomod2nix.toml
        run: nix develop --command gomod2nix generate

      - name: Create Pull Request
        env:
          GH_TOKEN: ${{ secrets.HOMEBREW_GITHUB_TOKEN }}
        run: |
          git diff --quiet gomod2nix.toml && exit 0
          BRANCH="chore/sync-gomod2nix"
          git config user.name "Floatpane Bot"
          git config user.email "us@floatpane.com"
          git checkout -b "$BRANCH"
          git add gomod2nix.toml
          git commit -m "chore: sync gomod2nix.toml"
          git push -f origin "$BRANCH"
          if ! gh pr list --head "$BRANCH" --state open | grep -q .; then
            BODY=$(cat <<'EOF'
          ## What?

          Regenerates `gomod2nix.toml` to reflect the current `go.mod` / `go.sum`.

          ## Why?

          Keeps the Nix build in sync with Go module changes. Without this, `nix build` fails when new or upgraded Go deps are missing from `gomod2nix.toml`. Generated automatically by the gomod2nix sync workflow.
          EOF
          )
            gh pr create --title "chore: sync gomod2nix.toml" --body "$BODY" --base master --label chore --label area/nix
          fi
