#!/bin/bash
#
# Copyright (C) 2023 MOXA Inc. All rights reserved.
# This software is distributed under the terms of the MOXA SOFTWARE NOTICE.
# See the file LICENSE for details.
#
# Authors:
#       2024  Wilson YS Huang  <wilsonys.huang@moxa.com>

source "${INSTL_SCRIPT_DIR}/lib/logger.sh"
log::init "${INSTL_LOG_FILE}" "${INSTL_LOG_LEVEL}"

set -e

install_prepare_debian_based() {
        local pkg_list

        pkg_list=("$@")

        for pkg in "${pkg_list[@]}"; do
                apt-get install -y "$pkg"
        done
}

install_prepare_redhat_based() {
        local pkg_list

        pkg_list=("$@")

        for pkg in "${pkg_list[@]}"; do
                yum install -y "$pkg"
        done
}

install_prepare() {
        local package_list

        log::debug "OS_PACKAGE_MANAGER=${OS_PACKAGE_MANAGER}"

        case "${OS_PACKAGE_MANAGER}" in
        "apt")
                package_list=(
                        "build-essential"
                        "linux-headers-$(uname -r)"
                        "dmidecode"
                        "dialog"
                )

                apt-get update
                install_prepare_debian_based "${package_list[@]}"

                if grep -q "gcc-12" "/proc/version"; then
                        apt-get install -y gcc-12
                fi
                ;;
        "yum")
                package_list=(
                        "kernel-devel-$(uname -r)"
                        "kernel-headers-$(uname -r)"
                        "dmidecode"
                        "dialog"
                )
                yum makecache
                yum groupinstall "Development Tools" -y
                install_prepare_redhat_based "${package_list[@]}"
                ;;

        *)
                return 1
                ;;
        esac

        return 0
}

main() {
        install_prepare >>"${INSTL_LOG_FILE}" 2>&1
}

main
