#!/bin/bash -e
#
# 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.
#

set -e

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

main() {
        log::info "Install hardware sensor monitor lm-sensors packages and configuration file"
        {
                udevadm control --reload-rules
                udevadm trigger
        } >>"${INSTL_LOG_FILE}"

        # i915 driver need to force probe on Elkhart lake before kernel 5.15
        if drv::is_loaded "i915" && ! util::is_exists "/dev/dri/card0" && [[ $(ver::compare "$LINUX_KERNEL_VER" "5.15") -lt 0 ]]; then
                log::info "Graphics device is not properly supported by the driver. Force probe it."
                {
                        local device_pci_id

                        for bus in "/sys/devices/pci0000:00/0000"*; do
                                # 0x030000 means VGA Display controller
                                if [[ "$(cat "$bus"/class)" == "0x030000" ]]; then
                                        device_pci_id=$(cat "$bus"/device 2>/dev/null)
                                        break
                                fi
                        done

                        if ! util::is_empty_str "$device_pci_id"; then
                                if ! grep -wq "i915.force_probe" "/etc/default/grub"; then
                                        sed -i "s/GRUB_CMDLINE_LINUX=\"[^\"]*/& i915.force_probe=${device_pci_id#"0x"}/" /etc/default/grub
                                        update-grub2
                                fi

                                if [[ "${LINUX_DISTRO_ID}" == "debian" ]]; then
                                        if add-apt-repository "deb http://deb.debian.org/debian/ bullseye main non-free"; then
                                                apt-get update
                                                apt-get install firmware-linux -y
                                        fi
                                fi
                        else
                                log::warn " Can not get graphics device PCI ID"
                        fi

                } >>"${INSTL_LOG_FILE}" 2>&1
        fi

        log::info "Install hardware sensor monitor lm-sensors packages and configuration file"
        {
                case "${OS_PACKAGE_MANAGER}" in
                "apt") apt-get install -y "lm-sensors" ;;
                "yum") yum install -y "lm_sensors" ;;
                esac
        } >>"${INSTL_LOG_FILE}"
}

main
