name: Build

on:
  workflow_dispatch:
    inputs:
      target:
        description: "Build target (e.g. aarch64 or aarch64_minimal)"
        default: "x86_64"
        type: string
      parallel:
        description: 'Massive parallel build of each image'
        default: true
        type: boolean
      name:
        description: "Name (for spin overrides)"
        default: "infix"
        type: string
      infix_repo:
        description: 'Repo to checkout (for spin overrides)'
        default: kernelkit/infix
        type: string
      infix_branch:
        description: 'Branch/tag/commit to checkout (for spin overrides)'
        default: ''
        type: string

  workflow_call:
    inputs:
      target:
        required: true
        type: string
      name:
        required: true
        type: string
      infix_repo:
        required: false
        type: string
        default: kernelkit/infix
      infix_branch:
        required: false
        type: string
        default: ''
        description: 'Branch/tag/commit to checkout (for spin overrides). Defaults to github.ref if not specified'
      parallel:
        required: false
        type: boolean
        default: true
      pre_build_script:
        required: false
        type: string
        default: ''
        description: 'Optional script to run after checkout (for spin customization)'
    secrets:
      CHECKOUT_TOKEN:
        required: false
        description: 'Token for cross-repository access'

env:
  NAME: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.name || inputs.name }}
  TARGET: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.target || inputs.target }}
  INFIX_REPO: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.infix_repo || inputs.infix_repo }}
  INFIX_BRANCH: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.infix_branch || inputs.infix_branch }}

jobs:
  build:
    name: Build ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.name || inputs.name }} ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.target || inputs.target }}
    runs-on: [ self-hosted, latest ]
    env:
      PARALLEL: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.parallel == 'true' || github.event_name != 'workflow_dispatch' && inputs.parallel == true }}
    strategy:
      fail-fast: false
    outputs:
      build_id: ${{ steps.vars.outputs.INFIX_BUILD_ID }}
    steps:
      - name: Cleanup Build Folder
        run: |
          ls -la ./
          rm -rf ./* || true
          rm -rf ./.??* || true
          ls -la ./

      - name: Checkout infix repo
        uses: actions/checkout@v4
        with:
          repository: ${{ env.INFIX_REPO }}
          ref: ${{ env.INFIX_BRANCH != '' && env.INFIX_BRANCH || github.ref }}
          clean: true
          fetch-depth: 0
          submodules: recursive
          token: ${{ secrets.CHECKOUT_TOKEN || github.token }}

      - uses: ./.github/actions/podman-cleanup

      - name: Run pre-build script
        if: ${{ inputs.pre_build_script != '' }}
        run: |
          cat > ./pre-build.sh << 'EOF'
          ${{ inputs.pre_build_script }}
          EOF
          chmod +x ./pre-build.sh
          bash ./pre-build.sh

      - name: Set Build Variables
        id: vars
        run: |
          if [ -n "${{ github.event.pull_request.head.sha }}" ]; then
              # Since PRs are built from an internally generated merge
              # commit, reverse lookups of PRs and/or commits from
              # image version information are cumbersome.  Therefore:
              # explicitly set a build id that references both the PR
              # and the commit.
              printf "INFIX_BUILD_ID=pr%d.%.7s\n" \
                  "${{ github.event.number }}" "${{ github.event.pull_request.head.sha }}" \
                  | tee -a $GITHUB_OUTPUT $GITHUB_ENV
          fi

          target=${{ env.TARGET }}
          name=${{ env.NAME }}
          echo "dir=${name}-${target}"        >> $GITHUB_OUTPUT
          echo "tgz=${name}-${target}.tar.gz" >> $GITHUB_OUTPUT
          echo "Building target ${target}_defconfig"

      - uses: ./.github/actions/cache-restore
        with:
          target: ${{ env.TARGET }}

      - name: Configure ${{ env.TARGET }}
        run: |
          make ${{ env.TARGET }}_defconfig

      - name: Cleanup stale containers and ports
        run: |
          podman rm -af || true
          pkill -9 -f rootlessport || true

      - name: Prepare parallel build
        id: parallel
        run: |

          if [ "$PARALLEL" == "true" ]; then
             echo "BR2_PER_PACKAGE_DIRECTORIES=y" >> output/.config
             MAKE="make -j$((`getconf _NPROCESSORS_ONLN` / 2 + 2))"
             echo "Building in parallel with -j$((`getconf _NPROCESSORS_ONLN` / 2 + 2))"
          else
             echo "Disabling parallel build"
             MAKE="make"
          fi
          echo "MAKE=$MAKE" >> $GITHUB_OUTPUT

      - name: Build ${{ env.TARGET }}
        run: |
          echo "Building ${{ env.TARGET }}_defconfig ..."
          eval "${{ steps.parallel.outputs.MAKE }}"

      - name:  Check SBOM from Build
        run: |
          make legal-info

      - name: Build test specification
        run: |
          make test-spec

      - name: Resulting size of build
        run: |
          printf "Size of complete tree : "
          du -sh .
          printf "Size of output/       : "
          du -sh output
          printf "Size of dl/           : "
          du -sh dl
          printf "Size of output/images/: "
          ls -l output/images/

      - name: Prepare ${{ env.TARGET }} Artifact
        run: |
          cd output/
          mv images ${{ steps.vars.outputs.dir }}
          ln -s ${{ steps.vars.outputs.dir }} images
          tar cfz ${{ steps.vars.outputs.tgz }} ${{ steps.vars.outputs.dir }}

      - uses: actions/upload-artifact@v4
        with:
          path: output/${{ steps.vars.outputs.tgz }}
          name: artifact-${{ env.TARGET }}
