name: ci

on:
  push:
    branches: ["main"]
  workflow_dispatch:

jobs:
  treefmt:
    runs-on: ubuntu-latest
    steps:
      - name: checkout code
        uses: actions/checkout@v6.0.1
      - name: install nix
        uses: https://github.com/cachix/install-nix-action@v31.8.4
      - name: set up nix
        run: |
          mkdir -p ~/.config/nix
          echo "experimental-features = nix-command flakes pipe-operators" >> ~/.config/nix/nix.conf
          nix-channel --add https://nixos.org/channels/nixos-unstable nixpkgs
          nix-channel --update
      - name: restore and save nix store
        uses: https://github.com/nix-community/cache-nix-action@v7
        with:
          primary-key: nix-${{ runner.os }}-${{ hashFiles('**/*.nix', '**/flake.lock') }}
          restore-prefixes-first-match: nix-${{ runner.os }}-
          gc-max-store-size-linux: 1G
          purge: true
          purge-last-accessed: "P1W"
          purge-prefixes: nix-${{ runner.os }}-
          purge-primary-key: never
      - name: set up nix-community cachix
        uses: https://github.com/cachix/cachix-action@v16
        with:
          name: nix-community
          authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}"
      - name: import gpg key
        env:
          GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
        run: |
          echo "$GPG_PRIVATE_KEY" | gpg --batch --import || true
          echo "default-cache-ttl 3600" >> ~/.gnupg/gpg-agent.conf
          echo RELOADAGENT | gpg-connect-agent
      - name: setup git identity
        run: |
          git config --global user.name "forgejo-actions-bot"
          git config --global user.email "actions@forgejo.local"

          KEYID=$(gpg --list-secret-keys --with-colons | awk -F: '/^sec/{print $5;exit}')
          git config --global user.signingkey "$KEYID"
          git config --global commit.gpgsign true
      - name: run nix fmt
        run: nix fmt
      - name: check for changes
        id: git_status
        run: |
          if [[ -n "$(git status --porcelain)" ]]; then
            echo "changed=true" >> $GITHUB_OUTPUT
          else
            echo "changed=false" >> $GITHUB_OUTPUT
          fi
      - name: commit and push changes
        if: steps.git_status.outputs.changed == 'true'
        env:
          FORGEJO_TOKEN: ${{ forgejo.token }}
          FORGEJO_REPOSITORY: ${{ forgejo.repository }}
        run: |
          git add -A
          git commit -S -m "style: autoformatting all files with treefmt"
          git push "https://${FORGEJO_TOKEN}@git.cpatino.com/${FORGEJO_REPOSITORY}.git" HEAD:main
