# Note: freebsd tests are not ran here (see integration instead)
name: job-test-unit

on:
  workflow_call:
    inputs:
      timeout:
        required: true
        type: number
      go-version:
        required: true
        type: string
      runner:
        required: true
        type: string
      canary:
        required: false
        default: false
        type: boolean
      windows-cni-version:
        required: true
        type: string
      linux-cni-version:
        required: true
        type: string
      linux-cni-sha:
        required: true
        type: string

env:
  GOTOOLCHAIN: local
  # Windows fails without this
  CGO_ENABLED: 0

jobs:
  test-unit:
    name: ${{ format('{0}{1}', inputs.runner, inputs.canary && ' (go canary)' || '') }}
    timeout-minutes: ${{ inputs.timeout }}
    runs-on: "${{ inputs.runner }}"
    defaults:
      run:
        shell: bash

    env:
      GO_VERSION: ${{ inputs.go-version }}

    steps:
      - name: "Init: checkout"
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683  # v4.2.2
        with:
          fetch-depth: 1

      # If canary is requested, check for the latest unstable release
      - if: ${{ inputs.canary }}
        name: "Init (canary): retrieve GO_VERSION"
        run: |
          latest_go="$(. ./hack/provisioning/version/fetch.sh; go::canary::for::go-setup)"
          printf "GO_VERSION=%s\n" "$latest_go" >> "$GITHUB_ENV"
          [ "$latest_go" != "" ] || \
            echo "::warning title=No canary go::There is currently no canary go version to test. Following steps will not run."

      - if: ${{ env.GO_VERSION != '' }}
        name: "Init: install go"
        uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5  # v5.5.0
        with:
          go-version: ${{ env.GO_VERSION }}
          check-latest: true

      # Install CNI
      - if: ${{ env.GO_VERSION != '' }}
        name: "Init: set up CNI"
        run: |
          if [ "$RUNNER_OS" == "Windows" ]; then
            GOPATH=$(go env GOPATH) WINCNI_VERSION=${{ inputs.windows-cni-version }} ./hack/provisioning/windows/cni.sh
          elif [ "$RUNNER_OS" == "Linux" ]; then
            ./hack/provisioning/linux/cni.sh install "${{ inputs.linux-cni-version }}" "amd64" "${{ inputs.linux-cni-sha }}"
          fi

      - if: ${{ env.GO_VERSION != '' }}
        name: "Run"
        run: |
          make test-unit

      # On linux, also run with root
      - if: ${{ env.GO_VERSION != '' && env.RUNNER_OS == 'Linux' }}
        name: "Run: with root"
        run: |
          sudo make test-unit
