name: Eval NixOS Configurations

on:
  check_suite:
    types: [completed]

permissions:
  contents: write

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          ref: deploy

      - name: Install Nix
        uses: cachix/install-nix-action@v25
        with:
          extra_nix_conf: |
            extra-trusted-public-keys = cache.garnix.io:CTFPyKSLcx5RMJKfLo5EEPUObbA78b0YQ2DTCJXqr9g=
            extra-substituters = https://cache.garnix.io

      - name: Configure Git
        run: |
          git config --global user.name "GitHub Actions Bot"
          git config --global user.email "actions@github.com"

      - name: Process Configurations
        run: |
          git checkout -b deploy-comin-eval
          mkdir -p eval
          hosts=$(nix flake show --json | jq -r '.nixosConfigurations | keys[]')
          echo "Found hosts: $hosts"

          failed_hosts=""
          for host in $hosts; do
            echo "Eval derivation for $host"
            if ! nix derivation show ".#nixosConfigurations.$host.config.system.build.toplevel" > "eval/$host.json"; then
              echo "❌ Failed to evaluate $host"
              failed_hosts+="$host "
              rm "eval/$host.json"
            else
              echo "✅ Successfully evaluated $host"
            fi
          done

          echo "Failed hosts: $failed_hosts" 
          
          git add eval/
          git commit -m "Update deployment configurations for all hosts"
          
          git push origin deploy-comin-eval