#!/bin/sh
##############################################################################
# If not stated otherwise in this file or this component's LICENSE file the
# following copyright and licenses apply:
#
# Copyright 2020 RDK Management
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################

set -x

. /etc/include.properties
. /etc/device.properties
. /etc/config.properties
. /lib/rdk/utils.sh

if [ -f /lib/rdk/xreInterfaceCalls.sh ];then
    . /lib/rdk/xreInterfaceCalls.sh
fi
# In case of RDK build it is done through separate script. Therefor adding Yocto guard is added here
if [ -f /etc/os-release ]; then
 if [ -d /opt/www/xrehtml ]; then
   rm -rf /opt/www/xrehtml
 fi
 if [ -d /opt/www/xrehtml_yocto ]; then
   rm -rf /opt/www/xrehtml_yocto
 fi
 touch /opt/gzenabled
 echo 1 > /opt/gzenabled
 if [ -f /opt/gzdisabled ] && [ "$BUILD_TYPE" != "prod" ]; then
   echo 0 > /opt/gzenabled
 fi
fi
# Yocto guard ends here

# Remove this file to be sure it won't be present on VBN/PROD builds.
# This is fix for ServiceManager ACL issues, for additional information
# see XRE-6426, XRE-7051
rm -f /opt/serviceManagerOverride.json

if [ ! -f /etc/os-release ]; then
     loop=1
     while [ $loop -eq 1 ]
     do
          if [ -f /tmp/.xre-startup ]; then
               loop=0
          else
               sleep 1
          fi
     done
fi

buildType=$BUILD_TYPE

if [ "$BUILD_TYPE" = "dev" -o "$BUILD_TYPE" = "vbn" ]; then
    PEM_FILE_PATH=/etc/ssl/certs/qt-cacert.pem
    if [ ! -f $PEM_FILE_PATH ]; then
        echo "WARNING: CA certificates container file $PEM_FILE_PATH does not exist!"
    else
        PEM_CONVERTING_DATE=`sed -n 's/^.*Certificate data from Mozilla as of: \(.*\)/\1/p' $PEM_FILE_PATH`
        if [ -n "$PEM_CONVERTING_DATE" ]; then
            PEM_CONVERTING_DATE_IN_SECONDS=$(date +%s -d "$PEM_CONVERTING_DATE")
            if [ -n "$PEM_CONVERTING_DATE_IN_SECONDS" ]; then
                DATE_DIFFERENCE_IN_DAYS=$(($(($(date +%s) - $PEM_CONVERTING_DATE_IN_SECONDS)) / 86400))
                if [ $DATE_DIFFERENCE_IN_DAYS -gt 150 ]; then
                    echo "WARNING: CA certificates in $PEM_FILE_PATH will expire in less than one month!"
                fi
            fi
        fi
    fi
fi

if [ -f $RDK_PATH/xre_soc.sh ]; then
    . $RDK_PATH/xre_soc.sh
else
    export PLATFORMROOT=/mnt/nfs/env
    export DtcpSrmFilePath=/mnt/nvram1/dtcp.srm
fi

if [ -f /etc/os-release ]; then
    export PLATFORMROOT=/home/root
fi

if [ "$DEVICE_TYPE" = "mediaclient" ]; then
    if [ ! -e $DtcpSrmFilePath ]; then
        touch $DtcpSrmFilePath
    fi
fi

#default using OpenGL

XRE_MODE=OGL
if [ "$3" != "" ]; then
     XRE_MODE=$2
fi

if [ ! -f /etc/os-release ]; then
    export PATH=$PATH:/usr/bin:/bin:/usr/local/bin:/sbin:/usr/local/lighttpd/sbin:/usr/local/sbin
    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/Qt/lib:/usr/local/lib
    export wrn_modules=bgst_ts_demux,bgst_audio_decoder

    # Checking the dependency module before startup
    nice sh $RDK_PATH/iarm-dependency-checker "XRE"

    cd /mnt/nfs/env
    NFS_MOUNT_POINT=/mnt/nfs
else
    export wrn_modules=bgst_ts_demux,bgst_audio_decoder
    cd /home/root
fi

if [ -f $RDK_PATH/cleanAdobe.sh ]; then
     nice sh $RDK_PATH/cleanAdobe.sh
fi

restartCount=0
export XDG_CONFIG_HOME=$PERSISTENT_PATH/.config
export FLASH_TEMP=$PERSISTENT_PATH/flashtmp
#runXRE log file (same as log file for receiver)
export RUNXRE_LOG_FILE=$LOG_PATH/receiver.log
export XRE_LOGS_DIR=$LOG_PATH
export SYSRESLOG_PATH=$LOG_PATH
export ADOBE_DRM_STORAGE_PATH=/opt/persistent/adobe
export FLASH_PERF_LOG_ENABLE=true
export LOG4C_RCPATH=/etc
export CEF_LOG_PATH=$LOG_PATH/cef.log

getLocationId()
{
     if [ -f $PERSISTENT_PATH/location.conf ] &&  [ "$buildType" != "prod" ]; then
          grep -v '^[[:space:]]*#' $PERSISTENT_PATH/location.conf
     else
	  if [ ! -f /etc/os-release ]; then
	      if [ "$buildType" != "dev" ]; then
	        echo "8666492704580837110"
	      else
                echo "9125754095508031110"
	     fi
	  else
	     echo "9125754095508031110"
	  fi
     fi
}

# Return system uptime in seconds
Uptime()
{
    cat /proc/uptime | awk '{ split($1,a,".");  print a[1]; }'
}

# check if Receiver is running and try to kill it. If it cannot be killed, then log this and reboot.
killReceiver()
{
    RECEIVER_LOG="/opt/logs/receiver.log"
    if [ -n "$(pidof Receiver)" ]; then
        echo "Receiver did not exit! Trying SIGTERM." >> ${RECEIVER_LOG}
        killall -TERM Receiver 2>/dev/null || true
        sleep 10
    fi
    if [ -n "$(pidof Receiver)" ]; then
        echo "Receiver cannot be killed with SIGTERM! Trying SIGABRT." >> ${RECEIVER_LOG}
        killall -ABRT Receiver 2>/dev/null || true
        sleep 10
    fi
    if [ -n "$(pidof Receiver)" ]; then
        echo "Receiver cannot be killed with SIGABRT! Trying SIGSEGV." >> ${RECEIVER_LOG}
        killall -SEGV Receiver 2>/dev/null || true
        sleep 10
    fi
    if [ -n "$(pidof Receiver)" ]; then
        echo "Receiver cannot be killed! Rebooting." >> ${RECEIVER_LOG}
        /rebootNow.sh -s ReceiverRecovery -o "Rebooting the box due to receiver process crash..."
    fi
}

#initializeXRE $NFS_MOUNT_POINT
# Call the device Specific Exports
if [ -f $RDK_PATH/deviceExports.sh ]; then
     source $RDK_PATH/deviceExports.sh
fi

if [ ! -f /etc/os-release ]; then
    mkdir -p $PERSISTENT_PATH/QT/home
    mkdir -p $PERSISTENT_PATH/QT/cache
    # setup XDG variables used by Qt5
    export TMPDIR=$PERSISTENT_PATH/QT/tmp
    export XDG_DATA_HOME=$PERSISTENT_PATH/QT/home
    export XDG_CACHE_HOME=$PERSISTENT_PATH/QT/cache
    export QT_QPA_EGLFS_HIDECURSOR=1
    export QT_QPA_FONTDIR=/usr/local/qt/lib/fonts
    export QWS_DATA_HOME=$PERSISTENT_PATH/QT/home
    export QWS_CACHE_HOME=$PERSISTENT_PATH/QT/cache
    #export QTWEBKIT_PLUGIN_PATH=/usr/local/lib
    export QT_QWS_FONTDIR=/usr/local/qt/lib/fonts/
    export LD_LIBRARY_PATH=/usr/local/lib:/usr/lib:/mnt/nfs/bin/target-snmp/lib/:/mnt/nfs/bin/:.
    export QTWEBKIT_PLUGIN_PATH=/usr/local/netscape/plugins
    export FONTCONFIG_PATH=/etc/fonts

##############################################################
# This MACRO is used by QTWebKit video plugin Implementation #
export BROADCOM_SIMPLE_CLIENT_XRE=yes
##############################################################
    export HOME=/
    #used by Flashplayer:
    #export HOME=/opt
else
    mkdir -p /opt/logs
    mkdir -p /opt/QT/home
    mkdir -p /opt/QT/tmp

    export QT_QPA_FONTDIR=/usr/share/fonts
    export FONTCONFIG_PATH=/etc/fonts
    export FONTCONFIG_FILE=/etc/fonts/fonts.conf

    export QWS_DATA_HOME=/opt/QT/home
    export QWS_CACHE_HOME=/opt/QT/cache
    export QWS_TMP_PATH=/opt/QT/tmp

    export XDG_CONFIG_HOME=/opt/.config
    export XDG_DATA_HOME=/opt/QT/home
    export XDG_CACHE_HOME=/opt/QT/cache

    export XRE_BLOCK_FULLSCREEN_TEXTURES=0
    export QT_QPA_EGLFS_HIDECURSOR=1
    export QT_QPA_PLATFORM=eglfs
    export DtcpSrmFilePath=/mnt/nvram1/dtcp.srm

    EVDEV_KB=" "
    EVDEV_MOUSE="-plugin EvdevMouse:/dev/event1"
fi

mkdir -p /opt/minidumps
ulimit -c unlimited

if [ -d /usr/local/bin/directfb/1.4 ]; then
    export DIRECTFB_VER='1.4'
else
    export DIRECTFB_VER='1.7'
fi

rm -f /opt/.gstreamer/registry.bin
export GST_REGISTRY="/opt/.gstreamer/registry.bin"
export GST_DEBUG=2

if [ "$DEVICE_TYPE" = "mediaclient" ]; then
    istsbEnabled=true
elif [ "$DEVICE_TYPE" = "hybrid" ]; then
    istsbEnabled=true
else
    istsbEnabled=false
fi

# Set the data dump properties
propertyFile="/etc/rmfconfig.ini"
if [ "$BUILD_TYPE" != "prod" ]; then
     if [ -f /opt/rmfconfig.ini ]; then
          propertyFile="/opt/rmfconfig.ini"
     fi
fi
if [ -f $propertyFile ]; then
      flag=`grep "RMF_USE_SOUPHTTPSRC" $propertyFile |grep -v "^[#]"| cut -d "=" -f2`
      if [ "$flag" ] && [ "$flag" = "TRUE" ]; then
              export RMF_USE_SOUPHTTPSRC=true
      fi
      
      #Check for USE.GENERIC.GSTREAMER.TEE value in rmfconfig.ini
      flag=`grep "USE.GENERIC.GSTREAMER.TEE" $propertyFile |grep -v "^[#]"| cut -d "=" -f2`
      if [ "$flag" ] && [ "$flag" = "TRUE" ]; then
              echo "flag is true - USE_GENERIC_GSTREAMER_TEE is true "
              export USE_GENERIC_GSTREAMER_TEE=true
      else
              echo "flag is false - USE_GENERIC_GSTREAMER_TEE is false "
              export USE_GENERIC_GSTREAMER_TEE=false
      fi
else
      echo "Not found configuration file - rmfconfig.ini .!"
fi

#log receiver start
echo `Timestamp` [runXRE] start sys_uptime=`Uptime` | tee -a $RUNXRE_LOG_FILE 

plat="${MANUFACTURE//_}_${RECEIVER_PLAT_TYPE//_}_${BUILD_VERSION//_}"
ocap=${OCAP_SUPPORT}

authTypesSetting="-authTypes=$AUTH_TYPES"
if [ "$AUTH_TYPES" == "" ]; then
    authTypesSetting=""
fi

reconnectReason=1

imageName=`grep "imagename:" /version.txt | cut -d":" -f2`
while :
do
    proxyport=`getProxyPort`
    proxyhost=`getProxyIp`
    url=`getXreURL`
    firstConnectUrl=`getFirstConnectURL`
    locationId=`getLocationId`
    export receiver_start=`Uptime`
    export AVE_CURL_DNS_CACHE_TIMEOUT=900
    export FONTCONFIG_FILE=/etc/fonts/fonts.conf

    XRE_ARGS=""
    if [ -f /opt/xre.qwebengine ]; then
        XRE_ARGS="--composite-to-mailbox"
    fi

    if [ -f /etc/os.release ]; then
        # yocto certificate file
        export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
    else
        # non-yocto certificate file
        export SSL_CERT_FILE=/etc/ssl/certs/qt-cacert.pem
    fi

    if [ -f /opt/SetEnv.sh ]  && [ "$BUILD_TYPE" != "prod" ]; then
        . /opt/SetEnv.sh
    fi

    # temporary fix until replaced with rdklogger-based logging
    XRE_ARGS="$XRE_ARGS --log-file=$CEF_LOG_PATH --enable-logging"

    echo "MOUNT POINT ${NFS_MOUNT_POINT}"
    if [ $XRE_MODE = "DFBXS" ]; then
	export dfb_clientid=0
	if [ ! -f /etc/os-release ]; then
            if [ "$buildType" != "dev" ] ; then
                /usr/local/bin/directfb/$DIRECTFB_VER/rundfb.sh join /mnt/nfs/env/Receiver -qws -display "directfb:videoonly:forcepremultiplied" -bg transparent -xreurl $url -deviceType="ipstb" -receiverPlatform=$plat -ocapSupport=$ocap -enableMdvr -monitorPower=true -reconnectReason=$reconnectReason -enableWebDiagnostics=true -webDiagnosticsUrl=http://127.0.0.1:50050/htmldiag/summary_info.html -stbImageName=$imageName -enableTsb=$istsbEnabled $authTypesSetting -firstConnectUrl $firstConnectUrl
            else
                /usr/local/bin/directfb/$DIRECTFB_VER/rundfb.sh join /mnt/nfs/env/Receiver -qws -display "directfb:videoonly:forcepremultiplied" -bg transparent -xreurl $url -deviceType="ipstb" -receiverPlatform=$plat -ocapSupport=$ocap -enableMdvr -monitorPower=true -reconnectReason=$reconnectReason -enableWebDiagnostics=true -webDiagnosticsUrl=http://127.0.0.1:50050/htmldiag/summary_info.html -disableServerHttpProxySettings=true -stbImageName=$imageName -enableTsb=$istsbEnabled $authTypesSetting -firstConnectUrl $firstConnectUrl
            fi
	else
            if [ "$buildType" != "dev" ] ; then
                /home/root/Receiver -qws -display "directfb:videoonly:forcepremultiplied" -bg transparent -xreurl $url -deviceType="ipstb" -receiverPlatform=$plat -ocapSupport=$ocap -enableMdvr -monitorPower=true -reconnectReason=$reconnectReason -enableWebDiagnostics=true -webDiagnosticsUrl=http://127.0.0.1:50050/htmldiag/summary_info.html -stbImageName=$imageName -enableTsb=true $authTypesSetting -firstConnectUrl $firstConnectUrl
            else
                /home/root/Receiver -qws -display "directfb:videoonly:forcepremultiplied" -bg transparent -xreurl $url -deviceType="ipstb" -receiverPlatform=$plat -ocapSupport=$ocap -enableMdvr -monitorPower=true -reconnectReason=$reconnectReason -enableWebDiagnostics=true -webDiagnosticsUrl=http://127.0.0.1:50050/htmldiag/summary_info.html -disableServerHttpProxySettings=true -stbImageName=$imageName -enableTsb=true $authTypesSetting -firstConnectUrl $firstConnectUrl
            fi
	fi
        
    else
        export clientid=0
	export dfb_clientid=1
        export DFB_DONT_INIT=""  
	if [ $DIRECTFB_VER = "1.7" ]; then
            export brcm_multiprocess_join_nexus=y
            echo "brcm_multiprocess_join_nexus = $brcm_multiprocess_join_nexus"
        fi
	if [ ! -f /etc/os-release ]; then
            if [ "$buildType" != "dev" ] ; then
                /usr/local/bin/directfb/$DIRECTFB_VER/rundfb.sh join /mnt/nfs/env/Receiver -qws -display "eglnullws:format=argb32:clientid=0" -xreurl $url -deviceType="ipstb" -receiverPlatform=$plat -ocapSupport=$ocap -a locationID=$locationId -enableMdvr -log -a mac=`getEstbMacAddress` -enableAuth  -a authVersion=14 -enableProxy -proxyHost $proxyhost -proxyPort $proxyport -monitorPower=true -enableHeartbeats -reconnectReason=$reconnectReason -enableDtcpIp=true -enableWebDiagnostics=true -webDiagnosticsUrl=http://127.0.0.1:50050/htmldiag/summary_info.html -stbImageName=$imageName $XRE_ARGS -enableTsb=$istsbEnabled $authTypesSetting -firstConnectUrl $firstConnectUrl
            else
                /usr/local/bin/directfb/$DIRECTFB_VER/rundfb.sh join /mnt/nfs/env/Receiver -qws -display "eglnullws:format=argb32:clientid=0" -xreurl $url -deviceType="ipstb" -receiverPlatform=$plat -ocapSupport=$ocap -a locationID=$locationId -enableMdvr -log -a mac=`getEstbMacAddress` -enableAuth  -a authVersion=14 -enableProxy -proxyHost $proxyhost -proxyPort $proxyport -monitorPower=true -enableHeartbeats -reconnectReason=$reconnectReason -enableDtcpIp=true -enableWebDiagnostics=true -webDiagnosticsUrl=http://127.0.0.1:50050/htmldiag/summary_info.html -disableServerHttpProxySettings=true -stbImageName=$imageName $XRE_ARGS -enableTsb=$istsbEnabled $authTypesSetting  -firstConnectUrl $firstConnectUrl
            fi
	else
            if [ "$buildType" != "dev" ] ; then
                /home/root/Receiver -qws -display "eglnullws:format=argb32:clientid=0" -xreurl $url -deviceType="ipstb" -receiverPlatform=$plat -ocapSupport=$ocap -a locationID=$locationId -enableMdvr -log -a mac=`getEstbMacAddress` -enableAuth  -a authVersion=14 -enableProxy -proxyHost $proxyhost -proxyPort $proxyport -monitorPower=true -enableHeartbeats -reconnectReason=$reconnectReason -enableDtcpIp=true -enableWebDiagnostics=true -webDiagnosticsUrl=http://127.0.0.1:50050/htmldiag/summary_info.html -stbImageName=$imageName $XRE_ARGS -enableTsb=true $authTypesSetting -firstConnectUrl $firstConnectUrl
            else
                /home/root/Receiver -qws -display "eglnullws:format=argb32:clientid=0" -xreurl $url -deviceType="ipstb" -receiverPlatform=$plat -ocapSupport=$ocap -a locationID=$locationId -enableMdvr -log -a mac=`getEstbMacAddress` -enableAuth  -a authVersion=14 -enableProxy -proxyHost $proxyhost -proxyPort $proxyport -monitorPower=true -enableHeartbeats -reconnectReason=$reconnectReason -enableDtcpIp=true -enableWebDiagnostics=true -webDiagnosticsUrl=http://127.0.0.1:50050/htmldiag/summary_info.html -disableServerHttpProxySettings=true -stbImageName=$imageName $XRE_ARGS -enableTsb=true $authTypesSetting -firstConnectUrl $firstConnectUrl
            fi
	fi
    fi 
    export receiver_exitcode=$?
    export receiver_signal=no
    export receiver_end=`Uptime`
    export receiver_uptime=`expr $receiver_end - $receiver_start`

    if [ $receiver_exitcode -ge 129 ] &&  [ $receiver_exitcode -le 255 ]
    then
	    export receiver_signal=`expr $receiver_exitcode - 128`
    fi
    firstConnect=false

    restartCount=`expr $restartCount + 1`                                       
    echo "restart count: $restartCount" >> $LOG_PATH/receiver.log
    #log receiver restart with some statistics
    echo `Timestamp` [runXRE] restart sys_uptime=`Uptime` rx_uptime=$receiver_uptime exitcode=$receiver_exitcode signal=$receiver_signal receiver_restarts=$restartCount

    if [ $receiver_signal == no ]
    then
        # the exit code holds the reason
        reconnectReason=$receiver_exitcode
    elif [ $receiver_signal -eq 6 ]
    then
    	# reconnect reason is 4 (dependent process failure) for signal 6 aborts
        reconnectReason=4
    elif [ $receiver_signal -eq 9 ]
    then
        # reconnect reason is 6 (kill signal received) for signal 9
        reconnectReason=6
    elif [ $receiver_signal -eq 15 ]
    then
    	# reconnect reason is 5 (sig term) for signal 15 (sigterm)
    	reconnectReason=5
    elif [ $receiver_signal -eq 8 ]
    then
    	# reconnect reason is 12 for signal 8 (sigfpe, issued by hang detector if gui thread doesn't reset watchdog timer)
    	reconnectReason=12
    else
    	# reconnect reason is 3 (receiver crash) for all other signals
    	reconnectReason=3
    fi
    if [ -f /tmp/rdk_xre_exitcode ]; then
       reconnectReason=`cat /tmp/rdk_xre_exitcode`
       rm /tmp/rdk_xre_exitcode
    fi
    if [ ! -f /tmp/rdk_xre_is_connected ]; then
       # if the receiver hasn't connected to xre then continue to show startup screens and reconnect reason should be bootup
       reconnectReason=1
    fi
    
    cp $TEMP_LOG_PATH/app_status.log $LOG_PATH/app_status_backup.log
    
    export crashTS=`date +%Y-%m-%d-%H-%M-%S`
    if [ "$POTOMAC_SVR" != "" ] && [ "$buildType" != "dev" ]; then
         nice sh $RDK_PATH/uploadDumps.sh $crashTS 1 $POTOMAC_SVR &
         nice sh $RDK_PATH/uploadDumps.sh $crashTS 0 $POTOMAC_SVR &
    else
         nice sh $RDK_PATH/uploadDumps.sh $crashTS 1&
         nice sh $RDK_PATH/uploadDumps.sh $crashTS 0&
    fi

    # This is a workaround for some cases during shutdown crash
    # when Receiver gets adopted by init (BCOM-455)
    if [ -n "$(pidof Receiver)" ]; then
       killReceiver
    fi

    sleep 1 
done
