#!/bin/bash

tmpFile=i2c_dev.tmp
defaultI2Cdev="i2c-3"

FORMAT_RED="\e[1;31m"
FORMAT_YELLOW="\e[1;93m"
FORMAT_GREEN="\e[1;32m"
FORMAT_BLUE="\e[1;36m"
FORMAT_DEFAULT="\e[0m"

info()
{
    echo -e ${FORMAT_YELLOW}
    echo "******************************************************************************************"
    echo $1
    echo "******************************************************************************************"
    echo -e ${FORMAT_DEFAULT}
}

info "Determining I2C GPIO device"

dev=$(i2cdetect -l)
#replace tab and line feed character with space
dev1=${dev//$'\t'/ }
devices=${dev1//$'\n'/ }

declare -a deviceList
k=0

IFS=' ' # space is set as delimiter
read -ra ADDR <<< "$devices"
for i in "${ADDR[@]}"
do 
    # only use devices that are named i2c-x
    if [[ $i == *"i2c-"* ]]; then
        deviceList[$k]=$i
        k=$k+1
    fi
done

# check on which bus the sensors of the HAT are available
# 0x68 is the address of the MPU sensor
for i in "${deviceList[@]}"
do 
    # i2c-
    dev=$(echo $i | cut -c5-)
    i2cdetect -y $dev 0x68 0x68 | grep 68 > /dev/null
    if [ $? -eq 0 ]
    then    
        echo $i > $tmpFile
        if [ $? -ne 0 ]
        then
            error "Could not write I2C GPIO device to file \"${tmpFile}\""
            exit 1
        fi

        info "I2C GPIO device: ${dev}"
        
        exit 0        
    fi        
done

echo $i > $tmpFile
if [ $? -ne 0 ]
then
    error "Could not write I2C GPIO device to file \"${tmpFile}\""
    exit 1
fi
info "I2C GPIO device (probing failed, using default): ${defaultI2Cdev}"

exit 1