#!/bin/bash

model=$(cat /etc/salicru/env)

# Stop the tcp service if is active
if (systemctl -q is-active device-modbus.service)
then
    MDB=true
else
    MDB=false
fi

# Stop the tcp service if is active
if (systemctl -q is-active device-modbus-tcp.service)
then
    MDB_TCP=true
else
    MDB_TCP=false
fi


Num1=$(cat /opt/scripts/device-modbus/constants.py | grep 'SLAVE_MODBUS =' | awk -F ' ' '{print $3}')

sudo sed -i -e "s/SLAVE_MODBUS = $Num1/SLAVE_MODBUS = ${1}/g" /opt/scripts/device-modbus/constants.py

Num2=$(cat /opt/scripts/device-modbus/constants.py | grep 'SERIAL_BAUD_RATE =' | awk -F ' ' '{print $3}')

sudo sed -i -e "s/SERIAL_BAUD_RATE = $Num2/SERIAL_BAUD_RATE = ${2}/g" /opt/scripts/device-modbus/constants.py

Num3=$(cat /opt/scripts/device-modbus/constants.py | grep 'SERIAL_BYTE_SIZE =' | awk -F ' ' '{print $3}')

sudo sed -i -e "s/SERIAL_BYTE_SIZE = $Num3/SERIAL_BYTE_SIZE = ${3}/g" /opt/scripts/device-modbus/constants.py

Num4=$(cat /opt/scripts/device-modbus/constants.py | grep 'SERIAL_STOP_BITS =' | awk -F ' ' '{print $3}')

sudo sed -i -e "s/SERIAL_STOP_BITS = $Num4/SERIAL_STOP_BITS = ${4}/g" /opt/scripts/device-modbus/constants.py

Num5=$(cat /opt/scripts/device-modbus/constants.py | grep 'SERIAL_PARITY =' | awk -F ' ' '{print $3}')

sudo sed -i -e "s/SERIAL_PARITY = $Num5/SERIAL_PARITY = '${5}'/g" /opt/scripts/device-modbus/constants.py

Num6=$(cat /opt/scripts/device-modbus/constants.py | grep 'TIME_OUT =' | awk -F ' ' '{print $3}')

sudo sed -i -e "s/TIME_OUT = $Num6/TIME_OUT = ${6}/g" /opt/scripts/device-modbus/constants.py

if [ "$model" == "cube40720" ] || [[ "$model" == *twinpro2* ]] || [[ "$model" == *twinrt2* ]] || [[ "$model" == *twinproA* ]] || [[ "$model" == *twinrtA* ]] || [[ "$model" == *advance* ]]; then
Num7=$(cat /opt/scripts/device-serial/constants.py | grep 'TCP_PORT =' | awk -F ' ' '{print $3}')
sudo sed -i -e "s/TCP_PORT = $Num7/TCP_PORT = ${7}/g" /opt/scripts/device-serial/constants.py
else
Num7=$(cat /opt/scripts/device-modbus/constants.py | grep 'TCP_PORT =' | awk -F ' ' '{print $3}')
sudo sed -i -e "s/TCP_PORT = $Num7/TCP_PORT = ${7}/g" /opt/scripts/device-modbus/constants.py
fi

if $MDB
then
  sudo service device-modbus restart
fi

if $MDB_TCP
then
  sudo service device-modbus-tcp restart
fi

