# Copyright (c) 2021 Huawei Device Co., Ltd.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
if (os_level == "mini" || os_level == "small") {
  import("//build/lite/config/component/lite_component.gni")
} else {
  import("//build/config/clang/clang.gni")
  import("//build/ohos.gni")
}
import("//build/ohos/kernel/kernel.gni")

# it needs adaptation for more device target
kernel_image = ""
if (target_cpu == "arm") {
  kernel_image = "uImage"
} else if (target_cpu == "arm64") {
  kernel_image = "Image"
} else if (target_cpu == "riscv64") {
  kernel_image = "Image"
} else if (target_cpu == "x86_64") {
  kernel_image = "bzImage"
} else if (target_cpu == "loongarch64") {
  kernel_image = "vmlinuz.efi"
}

if (os_level == "mini" || os_level == "small") {
  build_ext_component("linux_kernel") {
    no_default_deps = true
    exec_path = rebase_path(".", root_build_dir)
    outdir = rebase_path("$root_out_dir")
    build_type = "small"
    product_path_rebase = rebase_path(product_path, ohos_root_path)
    command = "./kernel_module_build.sh ${outdir} ${build_type} ${target_cpu} ${product_path_rebase} ${board_name} ${linux_kernel_version}"
  }
} else {
  kernel_build_script_dir = "//kernel/linux/build"
  kernel_source_dir = "//kernel/linux/$linux_kernel_version"
  action("check_build") {
    script = "check_build.sh"
    sources = [ kernel_source_dir ]
    outputs = [ "$root_build_dir/kernel.timestamp" ]
    args = [
      rebase_path(kernel_source_dir, root_build_dir),
      rebase_path("$root_build_dir/packages/phone/images/$kernel_image"),
      rebase_path("$root_build_dir/kernel.timestamp"),
    ]
  }

  action("build_kernel") {
    script = "build_kernel.sh"
    sources = [ kernel_source_dir ]

    deps = [ ":check_build" ]
    product_path = "vendor/$product_company/$product_name"
    build_type = "standard"
    outputs = [ "$root_build_dir/packages/phone/images/$kernel_image" ]
    args = [
      rebase_path(kernel_build_script_dir, root_build_dir),
      rebase_path("$root_out_dir/../KERNEL_OBJ"),
      rebase_path("$root_build_dir/packages/phone/images"),
      build_type,
      target_cpu,
      product_path,
      device_name,
      linux_kernel_version,
    ]
  }

  group("linux_kernel") {
    deps = [ ":build_kernel" ]
  }
}