#!/bin/bash

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

# --- Pre Tests ---
## Change constant to /dev/ttyO4 if it is necessary
if grep -wq $FILE -e 'ttyO2'; then 
   sed -i 's/ttyO2/ttyO4/g' $FILE
   service device-modbus restart
   sleep 40
fi
## Change initial value to 250V if it is necessary
value=$(curl -s localhost:5001/api/data/20514)
value=$(echo $value | awk '{print $2}' | sed 's/.$//')
if [ "$value" != '250' ]; then
    curl -s -X PUT -H "Content-Type: application/json" -d '{"value": 250, "password": 2020}' localhost:5000/api/data/20514
fi

sleep 20

# --- Tests ---
#1) Read register
value=$(curl -s localhost:5001/api/data/20514 | awk '{print $2}' | sed 's/.$//')
if [ "$value" != '250' ]; then
    exit 1
fi

#2) Write register
curl -s -X PUT -H "Content-Type: application/json" -d '{"value": 265, "password": 2020}' localhost:5000/api/data/20514

#4) Read register
value=$(curl -s localhost:5001/api/data/20514 | awk '{print $2}' | sed 's/.$//')
if [ "$value" != '265' ]; then
    exit 1
else
    #Rewriting previous value
    curl -s -X PUT -H "Content-Type: application/json" -d '{"value": 250, "password": 2020}' localhost:5000/api/data/20514
fi

#5) Read register
value=$(curl -s localhost:5001/api/data/20514 | awk '{print $2}' | sed 's/.$//')
if [ "$value" != '250' ]; then
    exit 1
fi