name: Nix Format Check

on:
  pull_request:
  push:
    branches: [ master ]

jobs:
  check-format:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Install Nix
        uses: cachix/install-nix-action@v30
        with:
          extra_nix_config: |
            experimental-features = nix-command flakes

      - name: Install nixfmt
        run: nix profile install nixpkgs#nixfmt-rfc-style
        
      - name: Check Nix formatting
        run: |
          exit_code=0
          while IFS= read -r file; do
            if ! nixfmt "$file"; then
              echo "Error: Failed to format $file"
              exit_code=1
              break
            fi
          done < <(find . -name "*.nix" -type f)
          
          if [ $exit_code -eq 0 ]; then
            if git diff --quiet; then
              echo "All Nix files are properly formatted"
            else
              echo "Error: Some Nix files are not properly formatted"
              git diff
              exit 1
            fi
          else
            exit $exit_code
          fi