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

function is_module_loaded() {
        local mod_name
        mod_name=${1}

        lsmod | grep -w $mod_name &>/dev/null
}

function check_leading_zero_digit() {
        local digit
        digit=${1}

        [[ "$digit" =~ ^([1-9][0-9]*|0)$ ]]
}

function get_model_name_from_dmi_type12() {
        /usr/sbin/dmidecode -t 12 |
                grep "Option " |
                awk -F ':' '{print substr($2,1,11)}' |
                sed 's/ //g'
}

function get_model_name_from_dmi_type1() {
        /usr/sbin/dmidecode -t 1 |
                grep "Product Name" |
                awk -F ':' '{print $2}' |
                sed 's/ //g'
}

function bind_i2c_driver() {
		local master_device_name=$1
		local slave_device_name=$2
		shift 2
		local reg_addr=$@
		local i2c_num=0
		local ret=0

		for filename in /sys/bus/i2c/devices/i2c-*/name; do
				i2c_devname=$(cat ${filename})
				if [[ $i2c_devname == *"$master_device_name"* ]]; then
						i2c_devpath=$(echo ${filename%/*})
                        i2c_num=$(echo ${i2c_devpath} | cut -d '-' -f2)
						for addr in $reg_addr; do
								if [[ ! -e "${i2c_devpath}/${i2c_num}-00${addr##0x}" ]]; then
										echo "$slave_device_name $addr" > ${i2c_devpath}/new_device
										[[ $? -ne 0 ]] && ret=1
								fi
						done
				fi
		done

		echo $ret
}

function get_i2c_device_minor_number_list() {
		local i2c_device_name=$1
		local i2c_num=0
		local i2c_nums=()

		for filename in /sys/bus/i2c/devices/i2c-*/name; do
				i2c_devname=$(cat ${filename})
				if [[ $i2c_devname == *"$i2c_device_name"* ]]; then
						i2c_devpath=$(echo ${filename%/*})
                        i2c_num=$(echo ${i2c_devpath} | cut -d '-' -f2)
						i2c_nums+=($i2c_num)
				fi
		done

		echo "${i2c_nums[@]}"
}

function format_as_i2c_directory_name() {
		# Input example: i2c_number(e.g. 0, 1, 2, 3, ...) and device_address(e.g. 0x26, 0x27, ...)
		# Output example: 4-0026, 4-0027 ...
		
		local i2c_number=$1
		local device_address=$2

		echo "$i2c_number-00${device_address##0x}"
}

function get_board_index_from_eeprom() {
		local address=$1
		local offset=$2

		local i2c_num=$(/usr/sbin/i2cdetect -l | grep smbus | awk -F ' ' '{print $1}' | awk -F '-' '{print $2}')

		/usr/sbin/i2cget -y $i2c_num $address $offset 2>/dev/null
}
