#!/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"
log::init "${INSTL_LOG_FILE}" "${INSTL_LOG_LEVEL}"

main() {
        log::info "Rename serial device with ttyMX"
        cat <<EOF >/etc/udev/rules.d/99-moxa-x86-serial-naming.rules
KERNEL=="ttyS0"   DRIVERS=="serial"  MODE="0660" SYMLINK+="ttyM0"
KERNEL=="ttyS1"   DRIVERS=="serial"  MODE="0660" SYMLINK+="ttyM1"
KERNEL=="ttyUSB0" DRIVERS=="mxuport" MODE="0660" SYMLINK+="ttyM2"
KERNEL=="ttyUSB1" DRIVERS=="mxuport" MODE="0660" SYMLINK+="ttyM3"
KERNEL=="ttyUSB2" DRIVERS=="mxuport" MODE="0660" SYMLINK+="ttyM4"
KERNEL=="ttyUSB3" DRIVERS=="mxuport" MODE="0660" SYMLINK+="ttyM5"
KERNEL=="ttyUSB4" DRIVERS=="mxuport" MODE="0660" SYMLINK+="ttyM6"
KERNEL=="ttyUSB5" DRIVERS=="mxuport" MODE="0660" SYMLINK+="ttyM7"
KERNEL=="ttyUSB6" DRIVERS=="mxuport" MODE="0660" SYMLINK+="ttyM8"
KERNEL=="ttyUSB7" DRIVERS=="mxuport" MODE="0660" SYMLINK+="ttyM9"
EOF
        {
                udevadm control --reload-rules
                udevadm trigger
        } >>"${INSTL_LOG_FILE}"

        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}"

        cat <<EOF >/lib/modules-load.d/it87.conf
it87
EOF

        cat <<EOF >/lib/modules-load.d/i2c-dev.conf
i2c-dev
EOF

        if ! util::is_exists "/etc/sensors.d/"; then
                mkdir -p "/etc/sensors.d/"
        fi

        if ! util::is_exists "/etc/sensors.d/it8786.conf"; then
                adc_lsb_coeff="0.9"
                V3_3_Rin="6.19"
                V3_3_Rf="10"
                V5_Rin="10"
                V5_Rf="10"

                cat <<EOF >/etc/sensors.d/it8786.conf
chip "it8786-*"
    ignore in0
    ignore in1

    label in2 "V3.3"
    compute in2 @*$adc_lsb_coeff*(1+($V3_3_Rin/$V3_3_Rf)), @/($adc_lsb_coeff*(1+($V3_3_Rin/$V3_3_Rf)))
    set in2_min 3.3*0.9
    set in2_max 3.3*1.1

    label in3 "V5.0"
    compute in3 @*$adc_lsb_coeff*(1+($V5_Rin/$V5_Rf)), @/($adc_lsb_coeff*(1+($V5_Rin/$V5_Rf)))
    set in3_min 5.0*0.9
    set in3_max 5.0*1.1

    ignore in4
    ignore in5
    ignore in6
    ignore in7
    # VBat
    ignore in8

    ignore fan1
    ignore fan2
    ignore fan3

    label temp1 "SYSTEM"
    label temp2 "SYSTEM2"

    ignore temp3
    ignore intrusion0
EOF

        fi
}

main
