name: Populate Cachix

on:
  push:
    branches:
      - main
  schedule:
    - cron: '37 7 * * *'
  workflow_dispatch: {}

permissions:
  contents: read

concurrency:
  group: populate-cachix-${{ github.ref }}
  cancel-in-progress: false

env:
  CACHIX_CACHE_NAME: codex-desktop-linux
  CARGO_TERM_COLOR: always
  NIX_CONFIG: experimental-features = nix-command flakes
  CACHIX_AUTH_TOKEN: ${{ secrets.CACHIX_AUTH_TOKEN }}

jobs:
  populate:
    name: Build Nix flake outputs
    runs-on: ubuntu-latest
    timeout-minutes: 150
    steps:
      - uses: actions/checkout@v4

      - uses: cachix/install-nix-action@v31

      - name: Configure Cachix for push
        if: env.CACHIX_AUTH_TOKEN != ''
        uses: cachix/cachix-action@v17
        with:
          name: ${{ env.CACHIX_CACHE_NAME }}
          authToken: ${{ env.CACHIX_AUTH_TOKEN }}

      - name: Warn when Cachix push token is missing
        if: env.CACHIX_AUTH_TOKEN == ''
        run: |
          cat <<'EOF' >> "$GITHUB_STEP_SUMMARY"
          ## Cachix

          `CACHIX_AUTH_TOKEN` is not configured, so this run will build without pushing to Cachix.
          Add a write token for the `codex-desktop-linux` Cachix cache as a repository secret to populate it automatically.
          EOF

      - name: Build cacheable Nix outputs
        run: |
          set -euo pipefail
          nix build \
            .#codex-desktop \
            .#codex-desktop-computer-use-ui \
            .#codex-desktop-remote-mobile-control \
            .#codex-desktop-computer-use-ui-remote-mobile-control \
            .#installer \
            --no-link \
            --print-build-logs
          {
            echo "## Cachix population"
            echo ""
            echo "- Cache: \`${CACHIX_CACHE_NAME}\`"
            echo "- Built: \`.#codex-desktop\`"
            echo "- Built: \`.#codex-desktop-computer-use-ui\`"
            echo "- Built: \`.#codex-desktop-remote-mobile-control\`"
            echo "- Built: \`.#codex-desktop-computer-use-ui-remote-mobile-control\`"
            echo "- Built: \`.#installer\`"
          } >> "$GITHUB_STEP_SUMMARY"
