name: Continuous Integration

on:
  merge_group:
  push:
    branches: [main, staging, trying]
  pull_request:
    branches: [main]
  schedule:
    # UTC
    - cron: '48 4 * * *'

env:
  CARGO_TERM_COLOR: always

jobs:
  style:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: Swatinem/rust-cache@v2

      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: thumbv7em-none-eabihf
          components: rustfmt, clippy

      - run: cargo fmt --all -- --check
      - run: cargo check

      - run: cargo clippy --all-features -- -D warnings

  compile:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: thumbv7em-none-eabihf
          components: llvm-tools-preview

      - uses: Swatinem/rust-cache@v2

      - run: cargo install cargo-binutils

      - run: cargo build
      - run: cargo build --release

      - name: Extract Binary
        run: cargo objcopy --release --verbose -- -O binary booster-release.bin

      - name: Upload Artifacts
        uses: actions/upload-artifact@v4
        if: (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/develop')
        with:
          name: Firmware Images
          path: |
            target/*/release/booster
            booster-release.bin

  hitl-trigger:
    runs-on: ubuntu-latest
    if: ${{ github.event_name == 'merge_group' }}
    environment: hitl

    steps:
      - uses: LouisBrunner/checks-action@v1.1.1
        id: hitl-check
        with:
          repo: ${{ github.repository }}
          sha: ${{ github.event.head_commit.id }}
          token: ${{ github.token }}
          name: HITL Run Status
          status: in_progress
          details_url: "https://github.com/${{github.repository}}/actions/runs/${{github.run_id}}"
          output: |
            {"summary": "Starting..."}

      - uses: peter-evans/repository-dispatch@v1
        with:
          token: ${{ secrets.DISPATCH_PAT }}
          event-type: booster
          repository: quartiq/hitl
          client-payload: |
            {"github": ${{ toJson(github) }}, "check_id": ${{steps.hitl-check.outputs.check_id}}}

      - uses: fountainhead/action-wait-for-check@v1.0.0
        id: status
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          checkName: HITL Run Status
          ref: ${{ github.event.pull_request.head.sha }}
          # The HITL can be backlogged by multiple enqueues, where each can take up to 10 minutes.
          timeoutSeconds: 3600

      - name: "Check HITL Status"
        if: steps.status.outputs.conclusion != 'success'
        run: exit -1
