#!/bin/bash
#
# App hosting logging functions
#
# Copyright (c) 2017-2018 by Cisco Systems, Inc.
# All rights reserved 
#

APP_HOSTING_LOG_FILE="/var/log/app_hosting.log"
APP_HOSTING_LOG_EXEC="app_hosting_log_exec"

if [[ "$app_hosting_log_sourced" != true ]]; then
    app_hosting_log_sourced=true

    if [[ -f /etc/init.d/spirit_log.sh ]]; then
        source /etc/init.d/spirit_log.sh 
    fi 
fi 

#
# Log error to the app hosting log file 
#
function app_hosting_log_error
{
    app_hosting_log_console $*

    backtrace
}

#
# Log to file and console
#
function app_hosting_log_console 
{
    app_hosting_log_trim

    local DATE=`date`
    echo "$DATE ($0): $*" | tee -a ${APP_HOSTING_LOG_FILE}
}

#
# Log to file 
#
function app_hosting_log()
{
    app_hosting_log_trim
 
    local DATE=`date`
    echo "$DATE ($0): $*" >> $APP_HOSTING_LOG_FILE
}

#
# Trim the log file 
#
function app_hosting_log_trim()
{
    if [[ -f ${APP_HOSTING_LOG_FILE} ]]; then
        local logfilesize=`filesize ${APP_HOSTING_LOG_FILE}`
        local maxlogsize=1048576

        if [[ $logfilesize -ge $maxlogsize ]]; then
            #
            # Chop off the start of the file
            #
            sed -i '1,100d' ${APP_HOSTING_LOG_FILE}
        fi
    fi

}

#
# Log to file and (in xr-vm only) to syslog as well
#
function app_hosting_log_syslog
{
    local level=$1
    shift
    app_hosting_log "$@"

    if [[ -f /pkg/bin/logger ]]; then
        # Careful - if this is invoked directly from a login shell
        # rather than a script, $0 will be '-su' or similar,
        # which confuses basename, logger, etc. into thinking its' an option
        local tag
        shopt -q login_shell
        if [ $? -eq 0 ]; then
            tag=$SHELL
        else
            tag=`basename $0`
        fi
        # /pkg/bin/logger must be called from xrnns or it hangs indefinitely
        declare -F operns_to_xrnns_cmd &>/dev/null
        if [ $? -eq 0 ]; then
            operns_to_xrnns_cmd /pkg/bin/logger -s $level -t "$tag" "$@"
        fi
    fi
}

function app_hosting_log_syslog_error()
{
    app_hosting_log_syslog err "$@"
}

function app_hosting_log_syslog_warning() 
{
    app_hosting_log_syslog warning "$@"
}

function app_hosting_log_syslog_notice() 
{
    app_hosting_log_syslog notice "$@"
}

#
# Execute command and log to app hosting log file 
#
function app_hosting_log_exec()
{
    app_hosting_log "exec: $*"
    app_hosting_log "    : in cwd" `pwd`

    local prefix="`date -u`: -- "
    $* 2>&1 | sed "s/^/${prefix}/g" >>${APP_HOSTING_LOG_FILE} 2>&1
    
    app_hosting_log_trim
 
    return ${PIPESTATUS[0]}
}

#
# Log results to the log file and the console
#
function app_hosting_log_exec_console
{
    app_hosting_log "exec: $*"
    app_hosting_log "    : in cwd" `pwd`

    local PREFIX="`date -u`: -- "
    $* 2>&1 | sed "s/^/${PREFIX}/g" | tee -a ${APP_HOSTING_LOG_FILE}

    app_hosting_log_trim

    return ${PIPESTATUS[0]}
}
