#!/bin/sh
#
# Name: tmgr
# Date: 2011-03-08
# Author: Rene Lehfeld
# Copyright 2011, Nokia.
#

# change umask to 0 to solve problems related to LLPD
umask 0

# enable the possibility to get core files of binaries started from this script
ulimit -c unlimited

# Init script information
INIT_NAME="start_script.conf"

OPT_DIR="/opt/trs"
CCS_DIR="/opt/CCS"
OPT_TRSSHAREDLIBS_DIR="/opt/trssharedlibs"
if [ ! -d "${OPT_TRSSHAREDLIBS_DIR}" ]; then
    OPT_TRSSHAREDLIBS_DIR=''
fi

# ---------- Dest Path ------------------

TRS_LIB_DEST="${OPT_TRSSHAREDLIBS_DIR}/usr/lib64"
if [ ! -d "${TRS_LIB_DEST}" ]; then
    TRS_LIB_DEST="${OPT_TRSSHAREDLIBS_DIR}/usr/lib"
fi

TRS_BIN_DEST="${OPT_DIR}/bin"
TRS_ETC_DEST="${OPT_DIR}/etc"
TRS_CFG_DEST="/ffs/run/config/fzm"
TRS_DATA="/ffs/run/trs_data"
TRS_ACT_DEST="${TRS_DATA}/active"
TRS_DB_DEST="${TRS_DATA}/db"
TRS_SIM_DEST="${TRS_DATA}/sim"
TRS_KEYSTR_DEST="${TRS_ACT_DEST}/keystorage"
TRS_LOG_DEST="/ffs/run/logs"
TRS_SRV_DEST="${OPT_DIR}/srv"
#TAUF_CONF="${TRS_ACT_DEST}/tauf_config"
TAUF_SCRIPT="${TRS_BIN_DEST}/tauf/target"
TRS_TA_START="/opt/TA"

# Default runlevel
RUNLEVEL=4

# Symbolic constant from enum
RECOVER_DS=2

# Load init script configuration
[ -f "${TRS_SIM_DEST}/${INIT_NAME}" ] && . "${TRS_SIM_DEST}/${INIT_NAME}"

# Load init script for FSPD startup in TA MODE
[ -f "${TRS_TA_START}/${INIT_NAME}" ] && . "${TRS_TA_START}/${INIT_NAME}"

# Load product specific settings
PRODUCT_SETTINGS="${TRS_ETC_DEST}/product_settings"
[ -f "${PRODUCT_SETTINGS}" ] && . "${PRODUCT_SETTINGS}"

# Load networking script
NETWORKING="${TRS_ETC_DEST}/networking"
[ -f "${NETWORKING}" ] && . "${NETWORKING}"

# Individual Program information
PROGRAM_START="${TRS_BIN_DEST}/ukTmgr"
PROGRAM_STOP="${TRS_BIN_DEST}/ukTmgrKill"
PROGRAM_STATUS="${TRS_BIN_DEST}/ukTmgrShow"
PROGRAM_EEPROM="${TRS_BIN_DEST}/test_hlEeprom"
PROGRAM_ENVINFO="${TRS_BIN_DEST}/test_envInfo"

# Verify programs are installed
test -f $PROGRAM_START || exit 1
test -f $PROGRAM_STOP || exit 1
test -f $PROGRAM_STATUS || exit 1
test -f $PROGRAM_EEPROM || exit 1

export PATH="${TRS_BIN_DEST}:/sbin:/bin:$PATH"
export LD_LIBRARY_PATH="${TRS_LIB_DEST}:${CCS_DIR}:/usr/lib64:/lib64:/usr/lib:/lib:$LD_LIBRARY_PATH"

start_trswconfigMsg()
{
    case "${BTSOM_SIMULATED}" in
        yes|y|YES|Y)
           echo "Starting trswconfigmsg..."
           chmod 777 /ffs/run/trswConfigMsg
           /ffs/run/trswConfigMsg >/dev/null 2>&1 &
        ;;
    esac
}

check_config()
{
    ## determine program
    ${PROGRAM_ENVINFO} envInfoProductType >/dev/null 2>&1
    case $? in
        1) PROGRAM_RC="${TRS_ETC_DIR}/tmgr_start.rc.wcdma"
            PRODUCT_TYPE='FTM';;
        2) PROGRAM_RC="${TRS_ETC_DIR}/tmgr_start.rc.wimax"
            PRODUCT_TYPE='WMX';;
        3) PROGRAM_RC="${TRS_ETC_DIR}/tmgr_start.rc.lte"
            PRODUCT_TYPE='LTE (DCM)';;
        4) PROGRAM_RC="${TRS_ETC_DIR}/tmgr_start.rc.lte"
            PRODUCT_TYPE='LTE (WMP)';;
        #default: WCDMA
        *) PROGRAM_RC="${TRS_ETC_DIR}/tmgr_start.rc.wcdma"
            PRODUCT_TYPE='FTM';;
    esac

    # Enable Strongswan patch
    touch /etc/ftm_strongswan_patch
    chmod 0664 /etc/ftm_strongswan_patch

    # MicroRec specific initializations
    ${TRS_BIN_DEST}/test_envInfo envInfoProductType >/dev/null 2>&1
    case $? in
        7)  # create directory to store technical log
            mkdir -p /pns/vendorFM/trsw

            # Load crypto modules by default and enable null encryption
            modprobe /lib/modules/$(uname -r)/kernel/net/ipv4/esp4.ko
            echo 1 > /proc/sys/net/ipv4/esp_force_null_encryption 

            # Enable route lookup in main table
            echo 1 > /proc/sys/net/ipv4/ip_route_lookup_rt_main
            echo 1 > /proc/sys/net/ipv4/accept_packets_with_local_ipaddr ;;
    esac

    ## Detect unit type on K2
    PIU_TYPE="$(cat /proc/device-tree/board-identity/unit-id)"
    PROGRAM_RC="${TRS_ETC_DEST}/tmgr_start.rc.fzm"

    export PIU_TYPE
    export PRODUCT_TYPE
    TMGR_CONDITIONS=$PIU_TYPE

    case "${TEST_ADAPTER}" in
        yes|y|YES|Y)
            PROGRAM_RC="${PROGRAM_RC}.ta"
            ${TRS_BIN_DEST}/secfg_test iptest_ta_enable_ta_mode 1
            ;;
    esac

    test -f $PROGRAM_RC || exit 1

    # Print out product type
    echo "Starting on unit $PIU_TYPE for product: $PRODUCT_TYPE"

    # GFr: Check if Datastore is present when DS set to "recover"
    $PROGRAM_EEPROM getDsStartupHandling >/dev/null 2>&1
    if [ $? -eq $RECOVER_DS ]; then
        if [ ! -f "${TRS_DB_DEST}/persist.db" ]; then
            # no Datastore found: force creating default configuration
            $PROGRAM_EEPROM setDsStartupHandling defaultDS >/dev/null 2>&1
        fi
    fi

    if [ ! -f "${TRS_ACT_DEST}/obsai_conf.xml" ]; then
        cp -f "${TRS_SRV_DEST}/obsai_conf.xml" "${TRS_ACT_DEST}/obsai_conf.xml"
        chmod 777 "${TRS_ACT_DEST}/obsai_conf.xml"
    fi

    if [ ! -f "${TRS_ACT_DEST}/swdlBD.xml" ]; then
        VERSION=$(cat "${TRS_SRV_DEST}/targetBD.xml" | grep softwareReleaseVersion|tail -n 1 | FS="\"" awk 'BEGIN { FS = "\"" } ; { print $2 }')
        cp -f "${TRS_SRV_DEST}/targetBD.xml" "${TRS_ACT_DEST}/${VERSION}.xml"
        ln -sf "${VERSION}.xml" "${TRS_ACT_DEST}/swdlBD.xml"
    fi

    if [  -f "${TRS_SIM_DEST}/sma_sft_test.cfg" ];then
        chmod 777 "${TRS_SIM_DEST}/sma_sft_test.cfg"   
        cat "${TRS_ETC_DEST}/sma_sft_test.cfg">>"${TRS_SIM_DEST}/sma_sft_test.cfg" >/dev/null 2>&1
        chmod 777 "${TRS_SIM_DEST}/sma_sft_test.cfg"
    fi 

    # MT Usage - Copy default SCF file to config path to avoid running Auto-Connection.
    if [ -f "${TRS_ETC_DEST}/MT_SCF_LTE.xml" -o -f "${TRS_ETC_DEST}/MT_SCF_WCDMA.xml" ]; then
        if [ ! -f "$TRS_DB_DEST/persist.db" -a ! -f "$TRS_DB_DEST/config.xml" ]; then
            local PRODTYPE=`${PROGRAM_ENVINFO} envInfoProductType | head -n 1`
            if [ "x${PRODTYPE}" = "xPROD_LTE_WMP" ]; then
                cp -f "${TRS_ETC_DEST}/MT_SCF_LTE.xml" "${TRS_DB_DEST}/config.xml"
                chmod 777 "${TRS_DB_DEST}/config.xml"
            elif [ "x${PRODTYPE}" = "xPROD_WCDMA" ]; then
                cp -f "${TRS_ETC_DEST}/MT_SCF_WCDMA.xml" "${TRS_DB_DEST}/config.xml"
                chmod 777 "${TRS_DB_DEST}/config.xml"
            fi
        fi
    fi

    # RDu: delete persist.db if there is a candidate config file ready for activation
    if [ -f $TRS_ACT_DEST/config.xml -o -f $TRS_ACT_DEST/config_upgrade.xml ]; then
        echo "Found candidate Site Configuration File for activation..."
        echo "Deleting persistency database(s)."
        # delete persist.db and its backup
        rm -f $TRS_DB_DEST/persist.db
        rm -f $TRS_DB_DEST/persist.bak
    fi

    # RDu: delete activated SCF file and corrupt persist.db to prevent reset loop
    if [ -f $TRS_ACT_DEST/config_activated.xml ]; then
        echo "Site Configuration File previously activated... System did not reach READY state!"
        echo "Deleting Site Configuration File(s) and persistency database(s)."
        # delete suspect file
        rm -f $TRS_ACT_DEST/config_activated.xml
        # delete persist.db and its backup
        rm -f $TRS_DB_DEST/persist.db
        rm -f $TRS_DB_DEST/persist.bak
        # restore configuration using backup file
        echo "Restoring configuration using backup file..."
        mv -f $TRS_ACT_DEST/config_backup.xml $TRS_ACT_DEST/config.xml
    fi

    # Copy TAUF config files to config directory if not.
    if [ ! -d $TRS_CFG_DEST ]; then
        mkdir -p $TRS_CFG_DEST
    fi
    if [ ! -f $TRS_CFG_DEST/target.hconf ]; then
        cp -f $TRS_ETC_DEST/tauf_target.hconf $TRS_CFG_DEST/target.hconf >/dev/null 2>&1
        chmod 777 $TRS_CFG_DEST/target.hconf >/dev/null 2>&1
    fi

    # Dynamic Support from TAUF
    if [ ! -f $TRS_CFG_DEST/tauf_dynamic.sh -a -f $TAUF_SCRIPT/tauf_dynamic.sh ]; then
        cp -f $TAUF_SCRIPT/tauf_dynamic.sh $TRS_CFG_DEST/tauf_dynamic.sh
        chmod 777 $TRS_CFG_DEST/tauf_dynamic.sh
    fi
    # Get env's at Startup for MT.
    if [ -f $TAUF_SCRIPT/getenv.sh ]; then
        $TAUF_SCRIPT/getenv.sh
    fi

    return 0
}

init_trs_ip_env()
{
    TRS_LMP_IP=192.168.255.129
    if [ -e /tmp/lmp_addr.conf ]; then
        TRS_LMP_IP=`grep TRS_LMP_IP /tmp/lmp_addr.conf |awk -F"=" '{print $2}'`
    fi
    FCT_SYS_IP=192.168.255.1
    if [ -e /tmp/lmp_addr.conf ]; then
        FCT_SYS_IP=`grep FCT_SYS_IP /tmp/lmp_addr.conf |awk -F"=" '{print $2}'`
    fi
    MASTEROM_IP=192.168.255.16
    if [ -e /tmp/lmp_addr.conf ]; then
        MASTEROM_IP=`grep MASTEROM_IP /tmp/lmp_addr.conf |awk -F"=" '{print $2}'`
    fi
}

enable_highway_monitor()
{
    ${TRS_BIN_DEST}/trswStartup_init 2 4
    if [ $? -eq 0 ]; then
        echo "Highway Monitor (eth2) interface enabled."
    else
        echo "Error in enabling Highway Monitor (eth2) interface."
    fi
}

enable_dct_interface()
{
    ${TRS_BIN_DEST}/trswStartup_init 2 5
    if [ $? -eq 0 ]; then
        echo "DCT (eth4) interface enabled."
    else
        echo "Error in enabling DCT (eth4) interface."
    fi
}

enableRioPorts() 
{
    local HOST_BIT=`cat /sys/class/rio_adapter/rio0/host_bit`
    local tries
    if [ "$HOST_BIT" -eq 0 ]; then
        let tries=6
        while [ "$(cat /sys/class/rio_adapter/rio0/base_id | cut -c 7-10)" = "ffff" ]; do
            echo "waiting for RIO enumeration ($(cat /sys/class/rio_adapter/rio0/base_id):$(cat /sys/class/rio_adapter/rio0/port_ok))"
            sleep 10
            let --tries
            if [ $tries -lt 0 ]; then
                break
            fi
        done
        if [ "$(cat /sys/class/rio_adapter/rio0/base_id | cut -c 7-10)" = "ffff" ]; then
            echo "!!!!!!!!!!!!!!! RIO enumeration problems ($(cat /sys/class/rio_adapter/rio0/base_id):$(cat /sys/class/rio_adapter/rio0/port_ok)) !!!!!!!!!!!!!!!"
        fi
        # execute rio interface configuration script (BTS PS)
        echo "Execute RIO network setup script (BTS PS)..."
        /etc/rc.d/init.d/common.d/setuprionetwork
        echo "Execute RIO network setup script (BTS PS): DONE"
    fi

    if [ -e /ffs/run/addons/rio-elog.py ]; then
        set -o pipefail

        ret=0
        let i=3

        while [ $i -gt 0 ]; do
            PYTHONHOME=/usr /usr/bin/python /ffs/run/addons/rio-elog.py -p 4 -e1 0x1000 </dev/null
            if [ $ret -eq 0 ]; then
                ret=$?
            fi
            PYTHONHOME=/usr /usr/bin/python /ffs/run/addons/rio-elog.py -p 5 -e1 0x1000 </dev/null
            if [ $ret -eq 0 ]; then
                ret=$?
            fi
            PYTHONHOME=/usr /usr/bin/python /ffs/run/addons/rio-elog.py -p 6 -e1 0x1000 </dev/null
            if [ $ret -eq 0 ]; then
                ret=$?
            fi
            let --i
        done

        if [ $ret -ne 0 ]; then
            echo "####################################################"
            echo "##"
            echo "## disabling of Link Layer Security failed"
            echo "## traffic might not work"
            echo "##"
            echo "####################################################"
        fi
    fi
}

enableRandDPorts()
{
    iptables -A PREROUTING -t mangle -i eth4+ -p tcp -m multiport --dport 15001:15005,15007 -j ACCEPT
    iptables -A PREROUTING -t mangle -i eth4+ -p tcp -m multiport --dport 15001:15005,15007 -j RETURN
}

start_selogApp()
{
    ${TRS_BIN_DEST}/selogApp &
    disown %+
}

start_syscomRouter()
{
    local syscomRouter="${TRS_BIN_DEST}/syscomRouter"
    local destfilename="${TRS_SIM_DEST}/$1"
    local mrecConfigureSyscom="${TRS_BIN_DEST}/configureSyscom"
    local srcPort=$2
    local defDstPort=$3
    local type=$4
    local dstIp
    local srcIp
    local dstPort

    case "${1}" in
        udpcp.ip)
            local defSrcPort=$srcPort
            
            if [ -f $destfilename ]; then
                CONTENT=`cat $destfilename`
                mode=` echo $CONTENT | awk '{printf $1}'`
                if [ $mode = "MICROREC" ]; then
                    lteDstIp=` echo $CONTENT | awk '{printf $2}'`
                    lteDstPort=` echo $CONTENT | awk '{printf $3}'`
                    lteSrcIp=` echo $CONTENT | awk '{printf $4}'`
                    lteSrcPort=` echo $CONTENT | awk '{printf $5}'`
                    wcdmaDstIp=` echo $CONTENT | awk '{printf $6}'`
                    wcdmaDstPort=` echo $CONTENT | awk '{printf $7}'`
                    wcdmaSrcIp=` echo $CONTENT | awk '{printf $8}'`
                    wcdmaSrcPort=` echo $CONTENT | awk '{printf $9}'`
                    srcIp=$lteSrcIp
                else
                    dstIp=`     echo $CONTENT | awk '{printf $1}'`
                    dstPort=`   echo $CONTENT | awk '{printf $2}'`
                    srcIp=`     echo $CONTENT | awk '{printf $3}'`
                    srcPort=`   echo $CONTENT | awk '{printf $4}'`
                fi
            fi

            if [ "x$srcIp" = "x" ]; then        
                srcIp=$TRS_LMP_IP
            fi

            if [ "x$dstIp" = "x" ]; then
                dstIp=$MASTEROM_IP
            fi

            if [ "x$srcPort" = "x" ]; then
                srcPort=$defSrcPort
            fi

            ${TRS_BIN_DEST}/test_envInfo envInfoIfLMP > /dev/null
            ETH4_5=eth$? 
            ${TRS_BIN_DEST}/test_envInfo envInfoIfTRS > /dev/null
            ETH2_3=eth$? 
            echo "tmgr: use $ETH2_3 for TRS port and $ETH4_5 for LMP port"

            echo "Disable ${ETH4_5}..."
            ip link set ${ETH4_5} down
            echo "Disable ${ETH4_5}: DONE"

            echo "Configure ${ETH2_3}:1..."
            ip addr flush dev ${ETH2_3} label ${ETH2_3}:1
            ip addr add $srcIp/24 dev ${ETH2_3} label ${ETH2_3}:1
            echo "Configure ${ETH2_3}:1: DONE"
            ;;
        *)
            if [ -f $destfilename ]; then
                CONTENT=`cat $destfilename`
                for LINE in $CONTENT; do
                    case "$LINE" in
                        *:*)
                            dstIp=`  echo -e $LINE | cut -d ':' -f 1`
                            dstPort=`echo -e $LINE | cut -d ':' -f 2`
                            break
                    esac
                done
            fi

            if [ "x$dstIp" = "x" ]; then
                dstIp=$MASTEROM_IP
            fi

            srcIp=`ip -4 route get "$dstIp" | awk '{where = match($0, /src[[:space:]][[:space:]]*([^[:space:]]*)/, a); if (where) { split (substr($0, RSTART, RLENGTH), a, "[[:space:]][[:space:]]*"); print a[2] } }'`

            if [ "x$srcIp" = "x" ]; then
                srcIp=$TRS_LMP_IP
            fi
            ;;
    esac            

    if [ "x$dstPort" = "x" ]; then
        dstPort=$defDstPort
    fi

    echo $dstIp
    echo $dstPort
    echo $srcIp

    # Only for MicroRec, the udpcp.ip file format is different 
    if [ $1 = udpcp.ip ]; then
        if [ $mode = "MICROREC" ]; then
            echo "Start mrecConfigureSyscom in MICROREC-BTSOM_SIMULATED mode with type '$type' ..."
            $mrecConfigureSyscom lte $lteSrcIp $lteSrcPort $lteDstIp $lteDstPort UDPCP
            $mrecConfigureSyscom wcdma $wcdmaSrcIp $wcdmaSrcPort $wcdmaDstIp $wcdmaDstPort UDPCP
            echo "Start mrecConfigureSyscom in MICROREC-BTSOM_SIMULATED mode with type '$type': DONE"
        else
            echo "Start syscomRouter in BTSOM_SIMULATED mode with type '$type' ..."
            if [ "$type" != "LSM" ] ; then
                $syscomRouter "${type}Server" "${type}Client" $srcIp $srcPort $dstIp $dstPort UDPCP
            else
                $syscomRouter "${type}Server" "${type}Client" $srcIp $srcPort $dstIp $dstPort UDPCP RetainMsgHdr_YES
            fi
            echo "Start syscomRouter in BTSOM_SIMULATED mode with type '$type': DONE"
        fi
    else
        echo "Start syscomRouter in BTSOM_SIMULATED mode with type '$type' ..."
        if [ "$type" != "LSM" ] ; then
            $syscomRouter "${type}Server" "${type}Client" $srcIp $srcPort $dstIp $dstPort UDPCP
        else
            $syscomRouter "${type}Server" "${type}Client" $srcIp $srcPort $dstIp $dstPort UDPCP RetainMsgHdr_YES
        fi
        echo "Start syscomRouter in BTSOM_SIMULATED mode with type '$type': DONE"
    fi

}

is_file_exist() 
{
    local udpcpfile="${TRS_SIM_DEST}/$1"
    if [ -e "$udpcpfile" ]; then
        return 1
    fi

    return 0
}

enable_sctp_forward()
{
    is_file_exist SCTP_TEST_ENABLE
    if [ $? -eq 1 ]; then
        echo "SCTP_TEST_ENABLE file exists, START Configuring forward routes"

        local GatewayIp
        case "${TEST_ADAPTER}" in
            yes|y|YES|Y)
                GatewayIp=192.168.253.16
                ;;
            *)
                GatewayIp=192.168.253.19
                ;;
        esac

        if [ ! -z "$SCTP_GATEWAY" ]; then
            GatewayIp=$SCTP_GATEWAY
            echo "Overwriting default SCTP Gateway:$GatewayIp with $SCTP_GATEWAY"
        fi
        
        ip ru add fwmark 100 lookup 100 prio 20000
        ip ro add t 100 default via $GatewayIp

        echo "Forward route configurations DONE"

        echo "Start configure proc entries for sctp forwarding" 

        echo 1 > /proc/sys/net/ipv4/accept_packets_with_local_ipaddr
        echo 1 > /proc/sys/net/ipv4/ip_route_lookup_rt_main

        echo "Configure proc entries for sctp forwarding Done" 

    fi
}

preconfig_dct_mt_traffic()
{
    local PRODTYPE=`${TRS_BIN_DEST}/test_envInfo envInfoProductType | head -n 1`
    if [ "x${PRODTYPE}" = "xPROD_MULTIMODE_DCM" ]; then
        ${TRS_BIN_DEST}/test_envInfo envInfoUnitType >/dev/null 2>&1
        case $? in
            15)
                # Check if units is FCTA or FCTA'
                MODE=`cat /sys/class/rio_adapter/rio0/host_bit`
                echo

                if [ "X$MODE" = "X1" ] ; then
                    echo "*** Unit is operating as FCTA (DUT) ***"
                    ip addr flush dev eth5 label eth5:4
                    ip addr add 192.168.254.1/27 dev eth5 label eth5:4
                    ip link set mtu 1500 dev eth5
                    ip link set eth5 up
                fi 
                
                # Note: Dont change the order of rules inserted
                # Terminate the icmp packets destined to DCT interface in FCT
                iptables -A PREROUTING -i eth5+ -d 192.168.254.1 -t mangle -p icmp -j ACCEPT
                # Forward all icmp request for MT & DCT interface towards FSP
                iptables -A PREROUTING -i eth5+ -t mangle -p icmp -j MARK --set-mark 97
                
                # To forward DCT tcp/udp traffic
                iptables -A PREROUTING -i eth5+ -t mangle -d 192.168.254.64/27 -p tcp -j MARK --set-mark 97 
                iptables -A PREROUTING -i eth5+ -t mangle -d 192.168.254.64/27 -p udp -j MARK --set-mark 97
                # To forward MT tcp/udp traffic
                iptables -A PREROUTING -i eth5+ -t mangle -d 192.168.1.0/24 -p tcp -j MARK --set-mark 97 
                iptables -A PREROUTING -i eth5+ -t mangle -d 192.168.1.0/24 -p udp -j MARK --set-mark 97
                ;; 
            
            19)
                # Check if units is FCTE or FCTE'
                MODE=`cat /sys/class/rio_adapter/rio0/host_bit`
                echo 
                
                if [ "X$MODE" = "X1" ] ; then 
                    echo "*** Unit is operating as FCTE (DUT) ***"
                    ip addr flush dev eth4
                    ip addr add 192.168.254.1/27 dev eth4
                    ip link set mtu 1500 dev eth4
                    ip link set eth4 down
                    ip link set eth4 up
                    
                    echo 1 > /proc/sys/net/ipv4/conf/eth4/forwarding

                    # Note: Dont change the order of rules inserted
                    #  Rules for DCT traffic
                    #  Forward ICMP traffic to DCT interface forwards FSP
                    iptables -A PREROUTING -i eth4+ -d 192.168.254.64/27 -t mangle -p icmp -j MARK --set-mark 97
                    iptables -A PREROUTING -i eth4+ -d 192.168.254.1 -t mangle -p icmp -j ACCEPT
                    # To forward DCT tcp/udp traffic
                    iptables -A PREROUTING -i eth4+ -t mangle -d 192.168.254.64/27 -p tcp -j MARK --set-mark 97
                    iptables -A PREROUTING -i eth4+ -t mangle -d 192.168.254.64/27 -p udp -j MARK --set-mark 97

                    # Rules for MT traffic
                    # Forward ICMP traffic to MT interface forwards FSP
                    iptables -A PREROUTING -i eth5+ -t mangle -d 192.168.1.0/24 -p icmp -j MARK --set-mark 97
                    # To forward MT tcp/udp traffic
                    iptables -A PREROUTING -i eth5+ -t mangle -d 192.168.1.0/24 -p tcp -j MARK --set-mark 97 
                    iptables -A PREROUTING -i eth5+ -t mangle -d 192.168.1.0/24 -p udp -j MARK --set-mark 97

                elif [ "X$MODE" = "X0" ] ; then 
                    iptables -I PREROUTING -i eth4+ -t mangle -j MARK --set-mark 97
                fi
                ;; 
            
            *) echo "Wrong unit type"
                ;;
        esac 
        
    fi
}

# Add Necessary firewall rules for MicroRec MP/CP, DCT/MT forwarding 
# Create a routing table for MP/CP & DCT/MT forwarding
add_microrec_forwarding_rules()
{
    local PRODTYPE=`${PROGRAM_ENVINFO} envInfoProductType | head -n 1`
    
    if [ "x${PRODTYPE}" = "xPROD_MULTIMODE_DCM" ]; then
        
        # For MicroRec CP/MP forwarding
        grep "cp_mp_forwarding_table" /etc/iproute2/rt_tables
        if [ $? -ne 0 ]; then 
            echo 98  cp_mp_forwarding_table >> /etc/iproute2/rt_tables
        fi
        
        # For MicroRec MT/DCT forwarding
        grep "dct_mt_forwarding_table" /etc/iproute2/rt_tables
        if [ $? -ne 0 ]; then 
            echo 97 dct_mt_forwarding_table >> /etc/iproute2/rt_tables
        fi

        # To handle TTL==255 special case 
        ip rule add fwmark 98 lookup 98 prio 20000
        ip rule add fwmark 99 lookup 98 prio 20000 
        ip rule add fwmark 97 lookup 97 prio 20000
        ip rule add fwmark 96 lookup 97 prio 20000

        # To handle TTL==0 special case 
        ip rule add fwmark 94 lookup 97 prio 20000
        
        case "${BTSOM_SIMULATED}" in  
            yes|y|YES|Y) 
                # Since TA sRIO id is 0x130d
                ip route add table 98 default via 192.168.253.19
                ip route add table 99 default via 192.168.253.19
                ip route add table 97 default via 192.168.253.19
                ;;
            
                # In production the packets has to be forwarded to 0x120F        
            *)  ip route add table 98 default via 192.168.253.26
                ip route add table 99 default via 192.168.253.26
                ip route add table 97 default via 192.168.253.18
                ;;
        esac
        
        # Rules for Ike 
        iptables  -A PREROUTING -i eth3+ -t mangle -p esp             -j ACCEPT
        iptables  -A PREROUTING -i eth3+ -t mangle -p ah              -j ACCEPT
        iptables  -A PREROUTING -i eth3+ -t mangle -p udp --dport 500 -j ACCEPT
        
        iptables  -A PREROUTING -i eth3+ -t mangle -p esp             -j RETURN
        iptables  -A PREROUTING -i eth3+ -t mangle -p ah              -j RETURN
        iptables  -A PREROUTING -i eth3+ -t mangle -p udp --dport 500 -j RETURN
        
        # Rules for Emergency Packet 
        iptables  -A PREROUTING -i eth3+ -t mangle -p udp --sport 65532 --dport 65535 -j ACCEPT
        iptables  -A PREROUTING -i eth3+ -t mangle -p udp --sport 65532 --dport 65535 -j RETURN
        
        # To handle TTL=255 special case  
        iptables -I POSTROUTING -t mangle -m mark --mark 0x63 -j TTL --ttl-inc 1 
        iptables -I POSTROUTING -t mangle -m mark --mark 0x60 -j TTL --ttl-inc 1  # For MT traffic with 255 TTL
        iptables -I POSTROUTING -t mangle -m mark --mark 0x5F -j TTL --ttl-inc 1  # For traffic received on rio0m0

        # To handle TTL=0 special case  
        iptables -I POSTROUTING -t mangle -o rio0m0 -m mark --mark 94 -j TTL --ttl-set 0
    fi  
}

enable_secure_filetransfer_for_simulated_btsom()
{
    local SFT_CFG_FILE="${TRS_SIM_DEST}/sma_sft_test.cfg"

    if [ ! -s "${SFT_CFG_FILE}" ]; then
        mkdir -m 0775 -p "${TRS_ACT_SIM_DIR}"
        touch "${SFT_CFG_FILE}"
    fi

    local IPADDRESS=`ip -4 addr show eth1 label eth1 | awk '$1~/^inet/{print $2}' | awk -F/ '{print $1}'`

    /bin/cat "${SFT_CFG_FILE}" | /bin/sed -e "s#^\\(TRS_PRIVATE_IP:\\).*#\\1${IPADDRESS}#g" > "${SFT_CFG_FILE}.tmp"
    /bin/mv "${SFT_CFG_FILE}.tmp" "${SFT_CFG_FILE}"

    if ! grep -q -E '^TRS_PRIVATE_IP:' "${SFT_CFG_FILE}"; then
        echo "TRS_PRIVATE_IP:${IPADDRESS}" >> "${SFT_CFG_FILE}"
    fi
    if ! grep -q -E '^BTSOM_TFTP_SERV_IP:' "${SFT_CFG_FILE}"; then
        echo "BTSOM_TFTP_SERV_IP:$MASTEROM_IP" >> "${SFT_CFG_FILE}"
    fi

    chmod 664 "${SFT_CFG_FILE}"
}

add_microrec_ssh_https_blocking_rules()
{
    # DROP ssh and https packets on all the interfaces except eth5 (LMP)
    iptables -A PREROUTING -i eth2+ -t mangle -p tcp --dport 443 -j DROP
    iptables -A PREROUTING -i eth2+ -t mangle -p tcp --dport 22 -j DROP
    iptables -A PREROUTING -i eth3+ -t mangle -p tcp --dport 443 -j DROP
    iptables -A PREROUTING -i eth3+ -t mangle -p tcp --dport 22 -j DROP
}

start_tmgr()
{
    init_trs_ip_env

    export LOCAL_INADDR=127.0.0.1
    local syscomRouter="${TRS_BIN_DEST}/syscomRouter"
    local forwardSyscom="${TRS_BIN_DEST}/forwardSyscom"
    local PRODTYPE=`${PROGRAM_ENVINFO} envInfoProductType | head -n 1`
    echo "Start TRS based Applications for unit $PIU_TYPE"

    local is_btsomsimulated=0
    local is_testadapter=0

    case "${TEST_ADAPTER}" in
        yes|y|YES|Y)
            case "${TEST_ADAPTER_WAIT_DUT}" in
                no|n|NO|N)
                    ;;
                *)
                    #is_testadapter=1
                    ;;
            esac
            is_file_exist udpcp.ip
            if [ $? -eq 0 ]; then
                echo "udpcp.ip config file not exist, syscomRouter not started"
            else
                start_syscomRouter udpcp.ip 9012 9012 wIPCS >${TRS_LOG_DEST}/IpcsBridge.logs 2>&1 </dev/null
            fi
            # Start the RP1 forwarding apps on the TA
            $forwardSyscom TA oamCmnTrs TA rp1Btsom  >${TRS_LOG_DEST}/rp1FwdStartup.logs 2>&1 </dev/null
            $forwardSyscom TA rp1Trsw TRSW rp1Trsw  >>${TRS_LOG_DEST}/rp1FwdStartup.logs 2>&1 </dev/null
            start_syscomRouter soap.ip 13300 13001 RP1 >${TRS_LOG_DEST}/Rp1Bridge.logs 2>&1 </dev/null
            echo "Started RP1 forwarding apps for TA.. Done"
            ;;
        *) 
            # run the syscomRouter for RP1 and LicenseManagement
            case "${BTSOM_SIMULATED}" in
                yes|y|YES|Y)
                    export BTSOM_SIMULATED
                    #is_btsomsimulated=1

                    enable_secure_filetransfer_for_simulated_btsom

                    start_syscomRouter soap.ip 13300 13001 RP1 >${TRS_LOG_DEST}/Rp1Bridge.logs     2>&1 </dev/null
                    start_syscomRouter nmap.ip 13061 13060 LSM >${TRS_LOG_DEST}/LicenseBridge.logs 2>&1 </dev/null
                    $syscomRouter wIPCSServer lIPCSClient 192.168.255.129 9012 192.168.255.33 9012 UDPCP >${TRS_LOG_DEST}/IPCSBridge.logs 2>&1 </dev/null
                    ${TRS_BIN_DEST}/startNtp  >${TRS_LOG_DEST}/startNtp.logs 2>&1 </dev/null

                    ;;
                *)
                    if [ -e "${TRS_SIM_DEST}/Rp1Peer.conf" ]; then
                        rm -f "${TRS_SIM_DEST}/Rp1Peer.conf"
                    fi
            esac
            ;;
    esac

    enable_sctp_forward
    preconfig_dct_mt_traffic

    # start task manager, don't return
    local command="$PROGRAM_START -F -C $TMGR_CONDITIONS -s 6 -c 0 -f 0 -m 1 -l $RUNLEVEL $PROGRAM_RC"

    NFSINTERFACE=$(check_nfsboot)
    if [ "x${NFSINTERFACE}" != "x" ]; then
        export NFSINTERFACE
    fi
    exec $command </dev/null
}

create_pipe()
{
    local use_console=0

    case "${TEST_ADAPTER}" in
        yes|y|YES|Y)
            use_console=1
            ;;
    esac

    case "${BTSOM_SIMULATED}" in  
        yes|y|YES|Y)
            use_console=1
            ;;
    esac

    local without_tee
    if which tee >/dev/null 2>&1; then
        without_tee=0
    else
        without_tee=1
    fi

    local without_console
    if [ -c /dev/console ] && echo 2>/dev/null >/dev/console; then
        without_console=0
    else
        without_console=1
    fi
    local pipe_end
    if [ $use_console -ne 0 ] && [ $without_tee -eq 0 ] && [ $without_console -eq 0 ]; then
        # lower kernel print level
        printk=$(cat /proc/sys/kernel/printk|awk '{print $1}')
        if [ "$printk" -gt 3 ]; then
            echo 3 > /proc/sys/kernel/printk
        fi
        pipe_end='tee -a /dev/console'
    else
        pipe_end='cat'
    fi

    /bin/rm -f /tmp/ukTmgr_pipe
    /usr/bin/mkfifo -m 0600 /tmp/ukTmgr_pipe

    ($pipe_end < /tmp/ukTmgr_pipe 2>&1 | logger -t BTS_SW/tmgr) >/dev/null 2>&1 </dev/null &
    disown %+
}

main()
{
    if [ "x${START_TRSSW}" = "x" ]; then
        START_TRSSW=yes
    fi

    case "${START_TRSSW}" in
        yes|y|YES|Y)
            check_config

            if [ "$PIU_TYPE" = "FCTE" ]; then
                # Enable Highway-Monitor(eth2) interface for build-1 H/W
                enable_highway_monitor
                # Enable DCT (eth4) interface for build-1 H/W
                enable_dct_interface
                # Enable TCP ports in the range 15001:15005,15007
                enableRandDPorts
            fi

         # to allow master and slave boards communication 
          iptables -A INPUT -i eth4 -j ACCEPT

            start_tmgr
            ;;
        *)
            exec ${TRS_BIN_DEST}/ukTmgrListenOnCardReady </dev/null
            ;;
    esac
}

create_pipe

start_trswconfigMsg

main >/tmp/ukTmgr_pipe 2>&1
