#!/bin/bash

value=''
counter=0

FILE='/opt/scripts/device-modbus/constants.py'

# This makes sure that it always reads from slot232
if grep -wq $FILE -e 'ttyO4'; then 
   sed -i 's/ttyO4/ttyO2/g' $FILE
   service device-modbus restart
fi

# 200s timeout
while [ $counter -lt 40 ] && ( [ -z "$value" ] || [ "$value" = "{}" ] ); do
    value=$(curl -s localhost:5000/api/data)
    #echo sleeping
    sleep 5
    counter=$((counter + 1))
done

model=$(cat /home/nimbus/release.txt | grep BM724 > /dev/null; echo $?)

if [ $model -eq 0 ]; then
    echo "mini"
    result1=false
    result2=false
    result3=false
    
    code1=$(/opt/scripts/device-panel/bin/hardware/MINI/rw_232slot > /dev/null; echo $?)
    if [ $code1 -eq 0 ]; then
        result1=true
    fi

    code2=$(/opt/scripts/device-panel/bin/hardware/MINI/rtc > /dev/null; echo $?)
    if [ $code2 -eq 0 ]; then
        result2=true
    fi

    code3=$(/opt/scripts/device-panel/bin/hardware/MINI/digital_io > /dev/null; echo $?)
    if [ $code3 -eq 0 ]; then
        result3=true
    fi

    json_content="{ \
\"test1\": $result1, \
\"test2\": $result2, \
\"test3\": $result3,
\"test4\": false,
\"test5\": false
}"

    echo "$json_content" > /opt/scripts/device-panel/bin/hardware/testsResults.json


else
    echo "maxi"

    result1=false
    result2=false
    result3=false
    result4=false
    result5=false
    
    code1=$(/opt/scripts/device-panel/bin/hardware/MAXI/rw_232slot > /dev/null; echo $?)
    if [ $code1 -eq 0 ]; then
        result1=true
    fi

    code4=$(/opt/scripts/device-panel/bin/hardware/MAXI/rtc > /dev/null; echo $?)
    if [ $code4 -eq 0 ]; then
        result4=true
    fi

    code5=$(/opt/scripts/device-panel/bin/hardware/MAXI/digital_io > /dev/null; echo $?)
    if [ $code5 -eq 0 ]; then
        result5=true
    fi

    json_content="{ \
\"test1\": $result1, \
\"test2\": $result2, \
\"test3\": $result3, \
\"test4\": $result4, \
\"test5\": $result5 \
}"

    echo "$json_content" > /opt/scripts/device-panel/bin/hardware/testsResults.json

fi
