#!/bin/sh
#
# This script is used as a wrapper for SAOS CLI instances.
# It is responsible for the following:
#   - establishing an appropriate PATH variable for the SAOS CLI
#   - checking that sufficient memory exists to start a CLI session
#   - spawning a SAOS CLI session (via exec)
#
# This script currently assumes that it will only be invoked for interactive
# shell instances.  If this is not the case then the memory check may need
# to be skipped for non-interactive shells.

source /ciena/scripts/path_manipulation.sh

path_append /ciena/bin
path_append /ciena/scripts

# The DISCONNECT_DELAY is the time that the system will wait for the user
# to hit CTRL-C to allow a CLI during a low-memory situation.
#
DISCONNECT_DELAY=10     # seconds

# The MEMORY_THRESHOLD is currently set so that it will trigger when a CLI
# session will cause a softmem warning.  The softmem setting is currently
# 10M, and the rough estimate for the CLI footprint is 2M. So warn at 12M.
#
MEMORY_THRESHOLD=12288   # Kbytes

LOW_MEMORY_MESSAGE=\
"\n"\
"The system is low on memory. Starting a CLI session when the\n"\
"system is in this state may cause instability or crashes.\n"\
"\n"\
"Use CTRL-C to ignore this warning and start a CLI session.\n"\
"\n"
# -----------------------------------------------------------------------------
start_shell() {
    GRSEC_S=`/sbin/gradm -S`
    if [ "${GRSEC_S}" != "The RBAC system is currently disabled." ]; then
        /sbin/gradm -n r_leos
    fi
    
    if [ -e /ciena/lib*/libmemTrace.so ]; then
        export LD_PRELOAD="libmemTrace.so $LD_PRELOAD"
    fi

    exec /mnt/apps/bin/leos $*
}

# -----------------------------------------------------------------------------
disconnect_countdown() {
    count=$DISCONNECT_DELAY
    while [ "$count" -gt "0" ] ; do
        printf "\rDisconnecting in %2d seconds" $count
        sleep 1
        count=$((count-1))
    done
    echo
}

# main ------------------------------------------------------------------------

# grab provided arguments so that they can be used in a trap call if required
args="$*"

free_mem=$(awk 'BEGIN       { free=0   } \
                /^MemFree:/ { free+=$2 } \
                /^Buffers:/ { free+=$2 } \
                /^Cached:/  { free+=$2 } \
                /^Shmem:/   { free-=$2 } \
                END { print free }' /proc/meminfo)

if [ -n "$free_mem" ] ; then
    if [ "$free_mem" -lt "$MEMORY_THRESHOLD" ] ; then
        echo -e $LOW_MEMORY_MESSAGE
        trap 'echo ; start_shell $args' INT           # set up CTRL-C response
        disconnect_countdown
        exit 1
    fi
fi

start_shell $args
