name: Build CLeonOS

on:
  push:
  pull_request:
  workflow_dispatch:
    inputs:
      menuconfig_preset:
        description: "menuconfig preset (full/minimal/dev)"
        type: choice
        options:
          - full
          - minimal
          - dev
        required: false
        default: "full"
      menuconfig_overrides:
        description: "Optional extra menuconfig args, e.g. --set CLEONOS_CLKS_ENABLE_AUDIO=OFF"
        required: false
        default: ""

permissions:
  contents: read

jobs:
  build-os:
    runs-on: ubuntu-latest
    env:
      MENUCONFIG_PRESET: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.menuconfig_preset || 'full' }}
      MENUCONFIG_OVERRIDES: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.menuconfig_overrides || '' }}

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          submodules: recursive

      - name: Install Dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y \
            build-essential \
            cmake \
            git \
            tar \
            xorriso \
            mtools \
            clang \
            lld \
            llvm \
            autoconf \
            automake \
            libtool \
            pkg-config \
            nasm

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Generate menuconfig (shared preset)
        shell: bash
        run: |
          set -euo pipefail
          extra_args=()
          if [[ -n "${MENUCONFIG_OVERRIDES}" ]]; then
            # shellcheck disable=SC2206
            extra_args=(${MENUCONFIG_OVERRIDES})
          fi
          python3 scripts/menuconfig.py --defaults --non-interactive --preset "${MENUCONFIG_PRESET}" "${extra_args[@]}"
          echo "menuconfig generated with preset=${MENUCONFIG_PRESET}"

      - name: Configure
        run: |
          cmake -S . -B build-cmake \
            -DCMAKE_BUILD_TYPE=Release \
            -DNO_COLOR=1 \
            -DCC=gcc \
            -DKERNEL_CXX=g++ \
            -DLD=ld.lld \
            -DUSER_CC=cc \
            -DUSER_LD=ld.lld \
            -DNM=llvm-nm \
            -DADDR2LINE=llvm-addr2line \
            -DLIMINE_REPO=https://github.com/limine-bootloader/limine.git

      - name: Build ISO
        run: cmake --build build-cmake --target iso -- -j"$(nproc)"

      - name: Upload ISO Artifact
        uses: actions/upload-artifact@v4
        with:
          name: cleonos-iso
          path: build/CLeonOS-x86_64.iso
          if-no-files-found: error
