name: Build binaries

on:
  workflow_dispatch:
    inputs:
      version:
        required: true
        type: string
  workflow_call:
    inputs:
      version:
        required: true
        type: string

jobs:
  binaries:
    name: Build lodestar binaries
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            platform: linux
            arch: amd64
          - os: lodestar-arm64-runner
            platform: linux
            arch: arm64
    runs-on: ${{matrix.os}}
    steps:
      - uses: actions/checkout@v4
      - name: Install arm64 specifics
        if: matrix.arch == 'arm64'
        run: |-
          # Install missing yarn
          # See https://github.com/github-early-access/arm-runners-beta/issues/5
          curl -fsSL --create-dirs -o $HOME/bin/yarn \
          https://github.com/yarnpkg/yarn/releases/download/v1.22.22/yarn-1.22.22.js
          chmod +x $HOME/bin/yarn
          echo "$HOME/bin" >> $GITHUB_PATH
          # Install missing build-essential
          sudo apt-get update
          sudo apt-get install -y build-essential python3
      - uses: "./.github/actions/setup-and-build"
        with:
          node: 22
      - run: |
          mkdir -p dist
          yarn global add @chainsafe/caxa@3.0.6
          npx caxa -m "Unpacking Lodestar binary, please wait..." -e "dashboards/**" -e "docs/**" -D -p "yarn install --frozen-lockfile --production" --input . --output "lodestar" -- "{{caxa}}/node_modules/.bin/node" "--max-old-space-size=8192" "{{caxa}}/node_modules/.bin/lodestar"
          tar -czf "dist/lodestar-${{ inputs.version }}-${{ matrix.platform }}-${{ matrix.arch }}.tar.gz" "lodestar"
      - name: Upload binaries
        uses: actions/upload-artifact@v4
        with:
          name: binaries-${{ matrix.os }}
          path: dist/
          if-no-files-found: error
      - name: Sanity check binary
        uses: actions/github-script@v7
        with:
          script: |
            exec.exec('./lodestar dev');
            await new Promise(resolve => setTimeout(resolve, 30000));
            const resp = await fetch('http://127.0.0.1:9596/eth/v1/node/version').catch(err => {
              core.setFailed(`Error accessing the API ${err}`);
              process.exit(1);
            });
            if (resp.status !== 200) {
              core.setFailed(`Failed to access API: ${resp.status}`);
              process.exit(1);
            }
            process.exit(0);
