#!/bin/sh
# Copyright (c) 2013 National Instruments.
# All rights reserved.

# Set stack size, OOM killer parameters, and environment, then
# start lvrt.

# save current lvrt_wrapper PID to $PID_LVRT_WRAPPER
echo $$ > $2


NIRTINI_ENABLE_CORE_DUMPS="section=LVRT,token=EnableCoreDumps"

log() {
	logger --tag lvrt-wrapper $@
}


# have to special-case serial# since that's not a valid identifier
export serialnum=`/sbin/fw_printenv -n serial# 2>/dev/null`
export DeviceCode=`/sbin/fw_printenv -n DeviceCode 2>/dev/null`
export DeviceDesc=`/sbin/fw_printenv -n DeviceDesc 2>/dev/null`
export TargetClass=`/sbin/fw_printenv -n TargetClass 2>/dev/null`
export nisafemodeversion=`/usr/local/natinst/bin/nisafemodeversion`

# stack size
ulimit -s 256

# core dump size
if [ "$(nirtcfg --get $NIRTINI_ENABLE_CORE_DUMPS,value=false | tr '[:upper:]' '[:lower:]')" = "true" ]; then
	log -p user.info "LVRT core dump size: $(ulimit -c)"
else
	# EnableCoreDumps is "false", unset, or some invalid value
	log -p user.info "LVRT core dumps are disabled."
	ulimit -c 0
fi

umask u=rwx,g=rwx,o=rx
echo 1000 > /proc/self/oom_score_adj
cd /usr/local/natinst/labview

# save $STARTUP_PARAM to environment variable LVRT_STATUS
export LVRT_STATUS=$1
# this variable is checked by code in:
### //labview/branches/{version}/dev/source/appcore/AppMagic.cpp and
### //labview/branches/{version}/dev/source/server/protocolerr.cpp

ARGS=
if [ "$3" == "true" ]; then
  ARGS=--ni-enable-ui
  [ "$DISPLAY" ] || export DISPLAY=:0
fi

exec ./lvrt $ARGS
