name: Nightly

on:
  schedule:
    - cron: "0 9 * * *"
  workflow_dispatch:

concurrency:
  group: nightly-release
  cancel-in-progress: false

permissions: {}

jobs:
  tag-nightly:
    name: Tag nightly
    runs-on: ubuntu-24.04-x86-32-cores
    environment: nightly
    permissions:
      contents: read
    env:
      CARGO_TERM_COLOR: always
    steps:
      - name: Mint GitHub App token
        id: app-token
        uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
        with:
          client-id: ${{ vars.FABRO_RELEASES_APP_CLIENT_ID }}
          private-key: ${{ secrets.FABRO_RELEASES_APP_PRIVATE_KEY }}

      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          fetch-depth: 0 # full history + tags for nightly probing
          persist-credentials: false

      - name: Skip if HEAD is already a nightly tag
        id: skip
        run: |
          last_tag=$(git describe --tags --match 'v*-nightly.*' --abbrev=0 2>/dev/null || true)
          if [[ -n "$last_tag" ]] && [[ "$(git rev-parse HEAD)" == "$(git rev-parse "$last_tag^{commit}")" ]]; then
            echo "HEAD already tagged as $last_tag — nothing to release."
            echo "skip=true" >> "$GITHUB_OUTPUT"
          fi

      - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
        if: steps.skip.outputs.skip != 'true'
        with:
          bun-version: 1.3.14
          no-cache: true

      - name: Install bun deps (for SPA verify)
        if: steps.skip.outputs.skip != 'true'
        run: bun install --frozen-lockfile

      - name: Set up Rust
        if: steps.skip.outputs.skip != 'true'
        uses: dtolnay/rust-toolchain@631a55b12751854ce901bb631d5902ceb48146f7 # stable
        with:
          toolchain: 1.97.1

      - uses: taiki-e/install-action@773334c0e05d7e699e4d78234494308223f3a2cf # nextest
        if: steps.skip.outputs.skip != 'true'

      - name: Release nightly
        if: steps.skip.outputs.skip != 'true'
        run: |
          git config user.name "fabro-releases[bot]"
          git config user.email "fabro-releases[bot]@users.noreply.github.com"
          release_token='${{ steps.app-token.outputs.token }}'
          git remote set-url origin \
            "https://x-access-token:${release_token}@github.com/${GITHUB_REPOSITORY}.git"
          unset release_token
          cargo --locked dev release --nightly
