#!/bin/ksh -p
#  exp_common: common functions
#  $Id: //depot/stable/explorer/lib/exp_common#2 $
EXP_COMMON_VERSION='$Revision: #2 $'
export EXP_COMMON_VERSION

EXP_VERSION=4.0

if [ -n "${DO_VERSION}" ]
then
    LIB=${0##*/}
    echo "${LIB} version: ${EXP_COMMON_VERSION}"
    exit
fi

#
# send output to the logfile, and stdout
# logfile foo is $foo
# logfile foo is $foo >/dev/null
# logfile <<EOF
#   this message
#   has two lines
# EOF
# date | logfile
#
logfile () {
    (
    MOD=${0##*/}

    # Check for writeability of EXP_LOGFILE
    if [ ! -w "${EXP_LOGFILE}" ]
    then
	# Check if we can create it
	touch ${EXP_LOGFILE} >/dev/null 2>&1
	if [ "$?" -ne 0 ]
	then
	    # Set to /dev/null if we can't write to logfile
	    EXP_LOGFILE=/dev/null
	fi
    fi

    if [ "$1" = "NOTNOISE" ]
    then
	shift
	if [ -n "${EXP_QUIET}" ]
	then
	    exec > /dev/null
	fi
    elif [ "$1" = "ERROR" -o "$1" = "FATAL" -o "$1" = "DEBUG" ]
    then
	# Do nothing on ERROR/FATAL messages, go to STDERR and logfile
	# Do not strip ERROR/FATAL from message
	LEVEL="$1 "
	shift
    else
	if [ -z "${EXP_VERBOSE}" ]
	then
	    exec > /dev/null
	fi
    fi
    {
	if [ "$#" -gt 0 ]
	then
	    echo "$*"
	else
	    cat
	fi
    } | sed -e "s/^/`date '+%b %d %H:%M:%S'` `uname -n`[${EXP_PID}] $MOD: ${LEVEL}/" | tee -a ${EXP_LOGFILE} 2>/dev/null
    )
}

prompt () {
    {
    if [ "$#" -gt 0 ]
    then
	echo "$*"
    else
        cat
    fi
    }
}

#
# run first arg; require a zero exit status
# 2nd arg is optional error message
# require "test `uname -s` = SunOS"
# require "uname -r | grep '^5'" "Must be run on SunOS 5.x"
#
require () {
    eval "$1" >/dev/null
    if [ "$?" -ne 0 ]
    then
	script=${0##*/}
	
	# FATAL if script is explorer
	if [ "$script" = "explorer" ]
	then
	    logfile FATAL "exited: ${2:-$1}"

	    # Log to /var/adm/messages if this is explorer
	    TEXT=`gettext "Explorer exited"`
	    logger -p daemon.notice -t explorer "${TEXT}"
	else
	    logfile NOTNOISE "exited: ${2:-$1}"
	fi

	exit 1
    fi
}
