#!/bin/bash
commonPath='/opt/scripts/common'

# Check if root
if [ "$EUID" -ne 0 ]
  then echo "Please run as root"
  exit 1
fi

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

if (systemctl -q is-active device-rccmd.service)
then
    emi=$(echo "$1" | grep emi3)
    re=$(echo "$1" | grep re3)

    systemctl stop device-rccmd
    if [ -z $emi ] || [ -z $re ]
    then	    
      RCCMD=true
    else 
      RCCMD=false  
    fi
else
    RCCMD=false
fi

if (systemctl -q is-active device-snmp.service)
then
    systemctl stop device-snmp
    SNMP=true
else
    SNMP=false
fi

if (systemctl -q is-active device-iec61850.service)
then
    systemctl stop device-iec61850
    IEC=true
else
    IEC=false
fi

if [ "$1" == "cube40720" ] || [[ "$1" == *twinpro2* ]] || [[ "$1" == *twinrt2* ]] || [[ "$1" == *twinproA* ]] || [[ "$1" == *twinrtA* ]] || [[ "$1" == *advance* ]]; then
    # Update new model
    systemctl stop device-serial
    cp -f /opt/scripts/device-serial/constants.$1.py /opt/scripts/device-serial/constants.py
    rm /etc/salicru/env
    echo $1 > /etc/salicru/env
    rm /etc/salicru/output_phase
    if [[ "$1" == *twin* ]] || [[ "$1" == *advance* ]] ; then
        echo 'mono' > /etc/salicru/output_phase
    else
        echo 'tri' > /etc/salicru/output_phase
    fi
    # Update device-mapper in case of modbus > serial change
    bash "${commonPath}/rename_mapper" device-modbus device-serial
    systemctl disable device-modbus
    systemctl stop device-modbus
    systemctl enable device-serial
else
    # Update new model
    systemctl stop device-modbus
    cp -f /opt/scripts/device-modbus/constants.$1.py /opt/scripts/device-modbus/constants.py
    rm /etc/salicru/env
    echo $1 > /etc/salicru/env
    rm /etc/salicru/output_phase
    if [ "$1" == "dcl" ] || [ "$1" == "dcs" ] || [ "$1" == "emi3" ] || [ "$1" == "re3" ]; then
        echo 'mono' > /etc/salicru/output_phase
    else
        echo 'tri' > /etc/salicru/output_phase
    fi
    # Update device-mapper in case of serial > modbus change
    bash "${commonPath}/rename_mapper" device-serial device-modbus
    #systemctl disable device-serial
    systemctl stop device-serial
    systemctl enable device-modbus
fi

# Restart device-mapper 
systemctl stop device-mapper
systemctl start device-mapper

if [ -e /lib/systemd/system/device-iec61850.service ]
then
    if [ "$1" == "dcs" ] || [ "$1" == "dcl" ]
    then
        systemctl start device-iec61850
    else
        systemctl stop device-iec61850
    fi
fi

# Start previously active services
if $TCP
then
    systemctl start device-modbus-tcp
fi

if $RCCMD
then
    systemctl start device-rccmd
fi

if $SNMP
then
    systemctl start device-snmp
fi

if $IEC
then
    systemctl start device-iec61850
fi
